Feature #10883
closed
Passing a block to itself
Added by Gondolin (Damien Robert) over 9 years ago.
Updated about 3 years ago.
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
Not exactly a duplicate, but also see the discussion at #6373
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
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.
Why itself
doesn't return itself?
It seems very confusing.
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 # ....
- Status changed from Open to Closed
Also available in: Atom
PDF
Like0
Like0Like0Like0Like0Like0Like0Like0