Sometimes we need to build a string.


'a'.tap { |it| it << 'b' } # => 'ab'

The above works because we mutate with << in the block which is then returned by tap.

'a'.tap { |it| it += 'b' } # => 'a'

We can’t use += as this is assignment and creates a new object instead of mutating the value returned by tap.


'a'.itself { |it| it << 'b' } # => 'a'

Using itself the block does not seem to be executed, e.g. 'a'.itself { raise } does not raise.

Update: All methods can accept a block which is sliently ignored if the method does not use it.


We could also use yield_self but this only works because << returns the new string.

'a'.yield_self { |it| it << 'b' } # => 'ab'

The result of the block is returned, not the reciver (original string):

'a'.yield_self { |it| it << 'b'; 'v' } # => 'v'