Project

General

Profile

Actions

Feature #10883

closed

Passing a block to itself

Added by Gondolin (Damien Robert) about 9 years ago. Updated over 2 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) about 9 years ago

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

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

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

Actions #5

Updated by baweaver (Brandon Weaver) about 9 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) over 8 years ago

Duplicate of: #6373, #10095

Actions #7

Updated by jeremyevans0 (Jeremy Evans) over 2 years ago

  • Status changed from Open to Closed
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0