Skip to main content

Deals You Can't Miss

1 Year Subscription

Exploiting tap in Ruby

The instance method tap is available as part of Object class from Ruby 1.9.x onwards. Rubyists exploit it to different use cases for fun and fashion. This blog post is to share my thoughts on what I think tap is best for.

Stackoverflow, the life-saver for many developers has one instance where the accepted correct answer to the use of tap is more misleading. This prompted me to write this blog post. To reproduce the accepted answer, it goes like below:

When readers encounters the code like below, they would have to follow all the three lines and then recognize that is is just creating an instance named user.
user =
user.username = "foobar"
user.password = "mypassword"
user.age = 15
The above code can be re-written as below to make the code immediately clear. A reader would not have to read what is inside the block to know that an instance user is created.
user = do |u|
  u.username = "foobar"
  u.password = "mypassword"
  u.age = 15
Based on my experience, in the context of real-world code, there should be many instances of code patterns like above. In such cases, it is much ideal to create an instance method of User like, say build, that is something like below than utilising tap.
class User
  attr_accessor :username, :password, :age
  def build(h)
    h.each do |k,v|
      sym = "#{k}=".to_sym
      self.send(sym, v) if self.respond_to?(sym)

u = :username => "ganesh", "password" => "mypass!!!", :age => 12, :sex => 'm'
p u

There is another example that states that tap can be used to contain related set methods within its block. I'd much rather build a composite method that contains all these methods within it than using method. It is this way I make my code more readable and concise.

Now you should be wondering, "What on earth can I use the "tap" method for? I'm so vying to exploit its potential."

I'd say the best use of tap method is for debugging and hardly anything else. To be specific, use tap to watch the value of an intermediate expression like below:
(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}"}
All the tap calls are meant for debugging the intermediate state of the expression in the chain-calls. Isn't this a lot better?

How tap works?

tap{|x|...} → obj
Yields x to the block, and then returns x. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.

And for your information, the example and explanation is shamelessly reproduced from Ruby doc.

ProTip: The best way to learn and digest Ruby phrases is to get into the habit of reading Ruby Doc.

More examples of how tap is used in intermediate expressions for debugging purposes
myobject.methods.sort.tap {|arr| p arr}.grep(/taint/)

(a + b) (p - q) / (a - b).tap {|denominator| puts denominator}

def meth
  return (some complex expression).tap {|result| puts result}


Ruby API Doc for Object#tap
MenTaLguY's blog titled, "Eavesdropping on expression"

My Popular Posts

Ten Commandments of Egoless Programming

We are nothing but the values we carry. All through my life thus far, I tried to influence people around me with the virtues I value. Thanks to some good reading habits I had inculcated, and the fortune of being in good community of peers and mentors alike, I managed to have read some real good books. This post is about the 10 commands of egoless programming in Weinberg's book. I shall explain the commandments based on my experience here. So very many decades ago, Gerald M. Weinberg authored  The Psychology of Computer Programming . In it, he listed The Ten Commandments of  Egoless Programming , which remains relevant even today for us as not just programmers but as team-members. Weinberg is regarded as a pioneer in taking a people-centric approach to computing, and his work endures as a good guide to intelligence, skill, teamwork, and problem-solving power of a developer. When they appear to inspire and instruct, we find that they can apply to just about every business area, and e

Should I buy refurbished laptop from Amazon?

This post is based on my experience with and guess it to be true on all other platforms as well. At least you can check out and verify for these pointers before you make that decision to buy renewed/refurbished laptop on Amazon with your hard earned money. I see this question propping up in several forums and on many different occasions. In the recent past, I had my 5 year old dell laptop that gave up because its motherboard failed. One of the options that I had in my mind was to re-use the HDD and the 16GB DDR4 RAM of that old laptop in the one that I purchase next as secondary.  I had come to a conclusion that it is not worth buying a refurbished/renewed laptop at all. Why? For the following reasons, most of which I see as BIG #RedFlags: You got to remember that Amazon provides a platform for 3rd party sellers to sell their products as well. So in your search for refurbished laptops you wouldn’t want to choose some random 3rd party seller who Amazon doesn’t endorse. You cou

Multi-tenant Architectures

  Multi-tenancy Application Deployment Architecture could be modeled in 4 broad ways: Separate Apps & Separate Databases Shared Apps & Shared Databases Separate Apps & Shared Databases Shared Apps & Separate Databases There is no right or wrong here. It's about choice and consequence that you should consider taking into your business context and constraints. In this post I intend to jot down a some key points to keep in mind for each of these multi-tenant architecture. These are more of quick notes for my quick reference, a cheat-sheet of sorts when I have to make choices. And I guess this can come handy to you too in your wise decision making. Separate Apps & Separate Databases Easiest to implement from development and deployment stand-point. Just automate the deployment infrastructure for every tenant for quick set-up. Most expensive of all the models from infrastructure cost stand-point. Relatively longer deployment t