The Tap method reminds me of Nightcrawler, the furry indigo teleporter from the Marvel Universe. He appears out of nowhere, kicks ass, and then disappears in a puff of smoke.
The Tap method, born in Ruby >= 1.9, is a helper method that yields a block on your object and returns the object. As a method, it looks like this:
class Object
def tap
yield self
self
end
end
This is especially useful when you are creating new classes because it allows you to assign properties from the get-go.
#Creating a new hero object
nightcrawler = Hero.new
nightcrawler.name = "Nightcrawler"
nightcrawler
#Refactored with tap
nightcrawler = Hero.new.tap{|h| name = "Nightcrawler"}
When you have many properties to set, this allows you to group all methods in an easy-to-read tap block.
nightcrawler = Hero.new.tap do |h|
h.name = "Nightcrawler"
h.power = "teleportation"
h.train_under_xavier
h.runaway
h.redemption
h.anything_else_you_want
end
Refactoring with tap can aid in readability. However, overdoing it with the tap blocks may result in the opposite. With great power, comes great responsibility.
Superpowers in mind, here’s the latest track from UK electro-duo Alunageorge. Goodbye for now.