Kernel#yield_self in Ruby 2.5.0

Hopefully in this year (2017) we will see Ruby 2.5.0 released.

There is an interesting feature that will be added — [Feature #6721].
It adds Kernel#yield_self method. That method is similar to Object#tap but instead of returning self, it returns result of execution of the block.

Let’s check simple example:

class Product
attr_accessor :name, :price, :weight
def initialize(name)
@name = name
end
  def add_delivery_costs
@price += (@weight > 100 ? 10 : 5)
end
end

Now we going to create new instance of Product and run tap method on it:

product = Product.new('Laptop')
product.tap do |p|
p.price = 100
p.weight = 50
p.add_delivery_costs
end

As a result, we will see something like this:

#<Product:0x007fc4f601fb18 @name="Laptop", @price=105, @weight=50>

As expected, at the end we have an instance of updated product.

But if we run same code with yield_self , we will see a different result:

product.yield_self do |p|
p.price = 100
p.weight = 50
p.add_delivery_costs
end

returns:

105

which is a result of execution of the block (last line from the block in our case).