what ruby tap method does on a {}

Subash picture Subash · Aug 27, 2014 · Viewed 9k times · Source

I've read about what tap does in Ruby but I'm confused by the code block below,

{}.tap do |h|
  # some hash processing
end

any help would be greatly appreciated.

Answer

Nikita Chernov picture Nikita Chernov · Aug 27, 2014

#tap method simply passes an object it was called on to a block. At the end of the block it returns the same object again. This way you can chain operations or restrict variable scope.

{}.tap { |h| h[:a] = 1 }.size # => 1

You were able to chain a next method to this block. And also avoided creating a h variable in your scope.