DEV Community

Andy Huynh
Andy Huynh

Posted on • Edited on

handy Ruby methods #2 - Object#tap

Clean and easy to read... name a better way to write Ruby apps. I'll wait.

If your Ruby code feels verbose, you're probably right! Matz (creator of Ruby) feels strongly about developer happiness. That involves less boilerplate which distracts you from saying the important things... like your business logic.

"The goal of Ruby is to make programmers happy.”

Yukihiro β€œMatz” Matsumoto

Object#tap is something I find myself returning to consistently at work. It makes what I'm saying more concise and reads better in my opinion.

Take this contrived example where we instantiate an Account, set a plan, save it and return the account:

account = Account.new
account.plan_name = "pro_monthly"
account.save!
account
Enter fullscreen mode Exit fullscreen mode

If you have symptoms of Dyslexia, this code will not help. The repetition of account is gaudy and in the words of Marie Kondo: "does not spark joy."

Marie Kondo Sparks Joy

This example also violates a software pattern called DRY (Don't Repeat Yourself). It's where we attempt to write the same thing again only if it's not necessary. I stress the latter because it's okay to repeat yourself with code when the opportunity presents itself. After all, writing software is about being pragmatic. Bending the rules when you have to is okay, just think it through first!

In this case, Ruby has a built in method to clean this up:

account = Account.new.tap do |a|
  a.plan_name = "pro_monthly"
  a.save!
end
Enter fullscreen mode Exit fullscreen mode

Three things make this code better 1) there's less to read 2) the object is set to account once 3) it feels more like Ruby. The last part is subjective but something you'll find yourself understanding as you continue writing Ruby. Take my word for it if you dare.

Same amount of lines as the first example, but a different kind of clarity in the second.

Top comments (3)

Collapse
 
cescquintero profile image
Francisco Quintero πŸ‡¨πŸ‡΄ • Edited

Successfully, used today twice Object#tap πŸ˜†βœŒπŸ½

Collapse
 
cescquintero profile image
Francisco Quintero πŸ‡¨πŸ‡΄

I think this method I've just used it once in my life xD. I tend to forget about it. Its usage reminds me of the typical case of new array, fill array, return array which can be solved with map.

Without Array#map

ary = []

something.each { |thing| ary << thing * 2}

ary

With Array#map

something.map { |thing| thing *2 }

Thanks for sharing, now I have a good example for this kind of situation and how to solve it with Object#tap 😁

Collapse
 
andy4thehuynh profile image
Andy Huynh

You got it!

Yeah, it's overkill but you can do something like this for the first example w/ tap:

something = (1..10)

[].tap do |arr|
  something.each { |num| arr << num * 2 }
end

This will return the array which is great in some cases.