Actions
Feature #10883
openPassing a block to itself
Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
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) about 6 years ago
Not exactly a duplicate, but also see the discussion at #6373
Updated by recursive-madman (Recursive Madman) about 6 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) about 6 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) about 6 years ago
Why itself
doesn't return itself?
It seems very confusing.
Updated by baweaver (Brandon Weaver) about 6 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