This blog is part of our Ruby 2.5 series.
Ruby 2.5 added a new method named yield_self. It yields the receiver to the given block and returns output of the last statement in the block.
How is it different from
try in Rails ?
Without a method argument
behaves similar to
It would yield to the given block
unless the receiver is nil
and returns the output of the last statement in the block.
Couple of differences to note are,
try is not part of
try’s main purpose is protection against
hence it doesn’t execute the block if receiver is
tap also is similar to
It’s part of Ruby itself.
The only difference is the value that is returned.
tap returns the receiver itself
yield_self returns the
output of the block.
improves readability of the code
by promoting chaining
over nested function calls.
Here is an example of both the styles.
yield_self is part of
hence it’s available to all the objects.