Last Updated: February 25, 2016
·
467
· bodacious

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

2 Responses
Add your response

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

over 1 year ago ·

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

over 1 year ago ·