Project

General

Profile

Feature #10883

Passing a block to itself

Added by Gondolin (Damien Robert) over 4 years ago. Updated almost 4 years ago.

Status:
Open
Priority:
Normal
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

History

Updated by phluid61 (Matthew Kerwin) over 4 years ago

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

Updated by recursive-madman (Recursive Madman) over 4 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) over 4 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) over 4 years ago

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

#5

Updated by baweaver (Brandon Weaver) over 4 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 # ....
#6

Updated by avit (Andrew Vit) almost 4 years ago

Duplicate of: #6373, #10095

Also available in: Atom PDF