Alexey
Alexey

Reputation: 4071

Is there a method in Ruby Object to pass itself to a block or proc?

I think it would be natural to have in Ruby something like:

class Object
  def yield_self
    yield(self)
  end
end

Does there exist a method like this by any chance? (I haven't found.) Does anybody else think it would be nice to have it?

Upvotes: 2

Views: 1127

Answers (3)

max pleaner
max pleaner

Reputation: 26788

yield_self has been added to ruby core a month ago as of June 2017. https://bugs.ruby-lang.org/projects/ruby-trunk/repository/revisions/58528

It's in ruby 2.5.0 after revision number 58528, although I'm not exactly sure how to get that code yet. Perhaps if someone knows how they can edit this answer

Upvotes: 3

Brandan
Brandan

Reputation: 14983

There is indeed the tap method that does almost exactly what you're asking:

x = [].tap do |array|
  array << 'foo'
  array << 9
end
p x

#=> ["foo", 9]

As Rob Davis points out, there's a subtle but important difference between tap and your method. The return value of tap is the receiver (i.e., the anonymous array in my example), while the return value of your method is the return value of the block.

You can see this in the source for the tap method:

VALUE
rb_obj_tap(VALUE obj)
{
    rb_yield(obj);
    return obj;
}

We're returning the obj that was passed into the function rather than the return value of rb_yield(obj). If this distinction is crucial, then tap is not what you need. Otherwise, it seems like a good fit.

Upvotes: 1

Gareth
Gareth

Reputation: 138240

I don't understand why you want the complexity of:

Object.new.yield_self do |foo|
  ...
end

When the following is almost exactly equivalent:

foo = Object.new
...

Upvotes: 1

Related Questions