问题
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?
回答1:
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
回答2:
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
...
回答3:
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.
来源:https://stackoverflow.com/questions/11423061/is-there-a-method-in-ruby-object-to-pass-itself-to-a-block-or-proc