Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what ruby tap method does on a {} [duplicate]

Tags:

ruby

tap

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.

like image 486
Subash Avatar asked Aug 27 '14 08:08

Subash


2 Answers

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

like image 144
Nikita Chernov Avatar answered Oct 22 '22 02:10

Nikita Chernov


tap is particularyl useful if you want to do some modifications on the hash and after that return it, e.g. inside a method that returns the hash. The advantage of tap being that you don't have to explitely return the hash at the end and there's no need for an intermediary variable.

hash = {}
hash[:a] = 'b'
hash
# => {:a=>"b"}

vs.

{}.tap do |hash|
  hash[:a] = 'b'
end
# => {:a=>"b"}
like image 44
koffeinfrei Avatar answered Oct 22 '22 02:10

koffeinfrei