Wei
Wei

Reputation: 13

ruby yield and return exist in one method simultaneously

What is point to have yield self and self in tap method. I think only yield self is enough.
The following code from Github faraday.rb

class Object
  def tap
    yield self
    self
  end unless Object.respond_to?(:tap)
end

Upvotes: 1

Views: 395

Answers (1)

Michael Kohl
Michael Kohl

Reputation: 66837

yield self passes self to the block tap is called with, whereas the self at the end is what tap returns. That's exactly the point of tap, using the object in a block and still being able to pass it on to the next method in the chain. Note however that if the block method is destructive, you'll pass on the modified version. Personally I try to avoid that, since I mostly use tap for debugging purposes.

Upvotes: 3

Related Questions