DEV Community

Discussion on: handy Ruby methods #2 - Object#tap

Collapse
 
cescquintero profile image
Francisco Quintero 🇨🇴

I think this method I've just used it once in my life xD. I tend to forget about it. Its usage reminds me of the typical case of new array, fill array, return array which can be solved with map.

Without Array#map

ary = []

something.each { |thing| ary << thing * 2}

ary

With Array#map

something.map { |thing| thing *2 }

Thanks for sharing, now I have a good example for this kind of situation and how to solve it with Object#tap 😁

Collapse
 
andy4thehuynh profile image
Andy Huynh

You got it!

Yeah, it's overkill but you can do something like this for the first example w/ tap:

something = (1..10)

[].tap do |arr|
  something.each { |num| arr << num * 2 }
end

This will return the array which is great in some cases.