Today I wanted to talk about a couple ways I think the .tap method in Ruby is useful. The first time a lot of us at Flatiron saw this method, it was used in an RSpec test and threw many of us for a loop trying to figure out exactly what the test was doing. After using the method for a bit, it’s become clearer what the tap method is, a shortcut.
So the three pieces of code above all return the same value with different ways of getting there. The tap method offers a few advantages over the others.
First, you get the same return out of a single line of code. This advantage should be obvious from looking at the code (you can paste the samples into IRB to confirm equality)
Second, you don’t need to call the variable to get the return value, which also means…
Third, you don’t have to store the object in a variable at all. This looks like…
This allows you if you are creating a large number of objects and passing them into a larger data structure (hash, database, array) to not have to first store the object in a variable before passing the variable into your data structure, saving steps along the way. With the other ways of making clifford ‘real’, you would need to store the object in a variable to be able to manipulate it after it was made, with .tap you can make clifford exist and have traits without ever having to tell the computer to remember him.
Make yourself useful.