Flatiron School Weekend Three – The Tap Method

Posted by Flatiron School  /  October 15, 2013

The following is a guest post by Samuel Owens and originally appeared on his blog. Samuel is currently in the Ruby-003 class at The Flatiron School. You can follow him on Twitter here.

Blog post image: tumblr_inline_muocumZGGk1rtan47.png

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.

Blog post image: tumblr_inline_muocvaoL1d1rtan47.pngBlog post image: tumblr_inline_muocvuEXw41rtan47.png

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…

Blog post image: tumblr_inline_muocwiQK5F1rtan47.png

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.