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
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."
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
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)
Successfully, used today twice
Object#tap
πβπ½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
With
Array#map
Thanks for sharing, now I have a good example for this kind of situation and how to solve it with
Object#tap
πYou got it!
Yeah, it's overkill but you can do something like this for the first example w/ tap:
This will return the array which is great in some cases.