Search code examples
rubytap

what ruby tap method does on a {}


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.


Solution

  • #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.