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

So, How tap is used ?

user = do |u|
u.username = "kartik"!

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

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

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 = do |u|

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) {|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 :

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.