Memorious Don't read this blog.

Ruby Tip of the Day: #tap

Have you ever encountered the following problem: you go to find out what's being returned by a method that's being called several places but you can't find a good place to add a puts? For example, let's say you had the following method called #full_name that's being called in 10 different places. How do you find what's being returned by #full_name in each instance with writing only one puts?

def full_name(first_name, last_name)
  "#{first_name.titlecase} #{last_name.titlecase}"

Your first thought is to probably create a variable like so:

def full_name(first_name, last_name)
  name = "#{first_name.titlecase} #{last_name.titlecase}"
  puts name

But there's a better way!

def full_name(first_name, last_name)
  "#{first_name.titlecase} #{last_name.titlecase}".tap { |name| puts name }

Here, we need no variable and yet the full name still gets returned. Moreover, our debug code is all at the end of one line instead of spread out over three lines.

The #tap method also works well with method chaining:

# before" ")

# after { |n| puts n.inspect }.join(" ")

Be sure to check out #tap the next time you need to inspect an element!

comments powered by Disqus