Skip to content

Instantly share code, notes, and snippets.

@krisleech
Last active August 28, 2019 10:06
Show Gist options
  • Select an option

  • Save krisleech/2f6bf3d702e5cebcd8dd9611be4c8ac0 to your computer and use it in GitHub Desktop.

Select an option

Save krisleech/2f6bf3d702e5cebcd8dd9611be4c8ac0 to your computer and use it in GitHub Desktop.
building a string

tap

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

We can't use += as this is assignment and creates a new object which is not returned:

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

itself

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

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

yield_self

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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment