简体   繁体   中英

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?

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

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
...

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 (ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM