Ruby: Tap that method

Kartik Jagdale
Jan 11, 2017 · 2 min read
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.


Aviacommerce is an open source e-commerce framework with an aim to simplify e-commerce ecosystem by creating and unifying smart services and providing consistent, cost-effective solution to sellers helping them sell more. visit to know more.

click the image to know more or visit

Kartik Jagdale

Written by



Aviabird Technologies provides enterprise software consulting in Angular, Rails, Elixir, Golang, React, Flutter and other technologies.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade