Project

General

Profile

Actions

Feature #10883

closed

Passing a block to itself

Added by Gondolin (Damien Robert) almost 10 years ago. Updated about 3 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:68217]

Description

In the discussion of itself
some people proposed that passing a block to itself could return the value of the block:

def itself
  if block_given?
    yield self
  else
    self
  end
end

It would be very usefull in method chains

#this would allow
an_array.foo.bar.itself {|x| x[1..x.length-1]}.baz
#which flows better than
a=an_array.foo.bar
a[1..a.length-1].baz

Updated by phluid61 (Matthew Kerwin) almost 10 years ago

Not exactly a duplicate, but also see the discussion at #6373

Updated by recursive-madman (Recursive Madman) almost 10 years ago

Note that for your example that wouldn't be needed:

a = an_array.foo.bar
a[1..a.length-1].baz

is equivalent to

an_array.foo.bar[1..-1].baz

Updated by shan (Shannon Skipper) almost 10 years ago

I think having a block form of #itself would be great. Here's a highly contrived example:

(("123".to_i - 3).to_s.reverse.to_i * 2).to_s
#=> "42"

Instead of nested parens, the following reads left to right:

"123".to_i.itself { |n| n - 3 }.to_s.reverse.to_i.itself { |n| n * 2 }.to_s
#=> "42"

It also allows a variety of other niceties:

["Hello", "Word"].itself { |greeting, subject| "#{greeting}... #{subject}!!" }
#=> "Hello... Word!!"

So like #tap except it returns itself instead of just tapping in.

Updated by nobu (Nobuyoshi Nakada) almost 10 years ago

Why itself doesn't return itself?
It seems very confusing.

Actions #5

Updated by baweaver (Brandon Weaver) almost 10 years ago

Nobuyoshi Nakada wrote:

Why itself doesn't return itself?
It seems very confusing.

Why can't we just tie into the current verbiage?

# Yes, contrived
1.yield { |v| v + 5 } # => 6

def defaults_to(default)
  -> v { v || default }
end

nil.yield(&defaults_to(5)).times do # ....
Actions #6

Updated by avit (Andrew Vit) about 9 years ago

Duplicate of: #6373, #10095

Actions #7

Updated by jeremyevans0 (Jeremy Evans) about 3 years ago

  • Status changed from Open to Closed
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0