Simpler = Better if it_gets_the_job_done

Arit Amana on September 27, 2019

Today at work, my teammate reviewed the following code I had written: In a nutshell, my build_page_data method builds an object called cat... [Read Full]
markdown guide

Theres no better feeling than slashing LOC by half + achieving better results and readability in the process. :)

BTW. Im just a JS guy, but i think ruby has this cool ||= operator that makes some things easier.

Can this:

categories[row[:group_id]] = format_data(row) unless categories[row[:group_id]].present?

Become this:

categories[row[:group_id]] ||= format_data(row)

and do the same?


ahhh yes you are right. Your comment finally made me go learn what "double-pipe equals" means in ruby 😄 so thank you!


First off, great post! I was worried at first that "David" was going to be unnecessarily critical of your PR, but it's awesome that his comments brought you to a number of useful refactors, and even better that you shared what you learned to help other new developers 😁

There's a subtle gotcha case with the or-assign operator, but it shouldn't occur in the context of this loop: let's say you have

something = {some_boolean: false}

something[:some_boolean] ||= true

The or-assign operator will take the falsey value* at something[:some_variable] and replace it with true. Similarly, the &&= operator will reassign variables that are truthy* (useful for cases like when you want to update values in a hash, but only if they already exist … and aren't false 😅)

*Rubyists love expressing ourselves in almost-words. falsey and truthy describe values that the double-negative patten will cast as !!foo == false and !!bar == true, respectively.


Glad i could help :)

The .presence thing is also a nice shortcut that I wish came to JS one day :)

code of conduct - report abuse