Traversing the Internets

Web Development in NYC

Flatiron School Weekend Three - the Tap Method

| Comments

#1 type of tap at the Flatiron School

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.

Equivalent Code…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Dog
attr_accessor :name, :favorite_food, :breed
end

# The Three code samples below all are based on the above class.

clifford = Dog.new.tap{|x| x.name = "Clifford"; x.favorite_food = "Children"; x.breed = "Big Red Dog"}

# The code above and below this comment are equivalent.

clifford = Dog.new

clifford.name = "Clifford"; clifford.favorite_food = "Children"; clifford.breed = "Big Red Dog"; clifford

# This code is also equal to the code below, in case semi-colons make you uncomfortable...

clifford = Dog.new
clifford.name = "Clifford"
clifford.favorite_food = "Children"
clifford.breed = "Big Red Dog."
clifford

Those kids should be screaming and jumping off that roller coaster.

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…

The Following Code Samples return the same value.
1
2
3
4
5
6
7
#Original code from above

clifford = Dog.new.tap{|x| x.name = "Clifford"; x.favorite_food = "Children"; x.breed = "Big Red Dog"}

#Same return value without having to store the object in a variable

Dog.new.tap{|x| x.name = "Clifford"; x.favorite_food = "Children"; x.breed = "Big Red Dog"}

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.

Comments