Rubyists! Tap and bang your way to more succinct code.
The problem:
You want to use a "bang" method in Ruby. Say, it's an Array that you want to reduce to only unique values, but you want to modify the current Array, instead of creating a new instance (which Array#uniq
does).
So you go with this approach:
x = my_array.uniq
That works when my_array
does indeed contain duplicate values, but when it doesn't, x
will be set to nil instead of an Array - potentially causing a bug in your code.
To prevent this, we normally have to throw the call to Array#uniq!
on a line of it's own:
x = my_array
x.uniq!
If you're counting, that's a 100% increase in the lines of code written!!!
The solution:
Use the Kernel#tap
method and pass the method name through as a symbol:
x = my_array.tap(&:uniq!)
The array is modified without creating a new instance, and there's no danger of it returning nil
Written by Gavin Morrice
Related protips
2 Responses

in your first example you forget !
x = my_array.uniq!

The solution is a 100% increase in complexity!!!