Ruby: Tap that method

Ruby Tap :)

Recently I came across a really cool method which will make our ruby code more readable and it is tap.

The feature is coded in ruby as shown below

class Object
def tap
yield self
self
end
end

So, How tap is used ?

user = User.new.tap do |u|
u.username = "kartik"
u.save!
end

Isn’t it pretty and simple than the old conventional method of creating a object.

# Old Dusty Traditional Method
user = User.new
user.username = "kartik"
user.save!

So, What it does ?

In Simple words, it just allows you do something with an object inside of a block, and always have that block return the object itself.

It was created for tapping into method chains.

Another overkilling extension of above example can be as below so get what I meant to say, Everything in a block and readable.

user = User.new.tap do |u|
u.build_profile
u.process_credit_card
u.ship_out_item
u.send_email_confirmation
u.blahblahblah
end

Tap for debugging method chains:

If you see most of the time it’s pretty much difficult to debug chained methods. Lets see it with below example.

If I have to debug the below expression :

(1..10).to_a.select {|x| x%2 == 0}.map {|x| x*x}

I would generally add pry debugger above the expression and execute each chain one by one in order to see whats happening. Which is somehow boring and tiresome when you have many one liners like this.

Tap to the rescue :

Same thing can be done using tap without disturbing the chain of expressions and getting immediate results after each chain execution.

(1..10).tap { |x| puts "original: #{x.inspect}" }.to_a.
tap { |x| puts "array: #{x.inspect}" }.
select { |x| x%2 == 0 }.
tap { |x| puts "evens: #{x.inspect}" }.
map { |x| x*x }.
tap { |x| puts "squares: #{x.inspect}" }

Conclusion :

Just like any other ruby syntactic sugar , I would say tap is a pretty cool ruby method which can not just be used for readability but also to debug chained methods. Give it a shot.

Signup for our latest Angular 2 Fundamentals course

Reference :

  1. http://apidock.com/rails/v2.3.8/Object/tap
Like what you read? Give Kartik Jagdale a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.