All Ruby on Rails Node JS Android iOS React Native Frontend

TIL #5: How to work with Conditional Assignment Operator

Conditional Assignment Operator!

The rules says:

A ||= B assigns B to A only if A is nil or false

So, what if A is actually nil or false? Should we care?

YES, especially when doing simple memoization technique. Lets consider simple case:

    def memoization
      @a ||= 2 # correct, assigns 2 to @a and returns on each method call
    end
but when the right side of an assignment evaluates to nil or false then something bad happen...
    def memoization
      @a ||= nil # memoization doesn't work as expected. It assigns nil to @a each time the method gets called!
    end
Just imagine the scenario when the right side of an assigment does some heavy calculations which returns nil or false as a result. They will run every single time!

 

Here you can find more sophisticated example with a way of how to handle a fix for it:

 

Worth reading:

http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html


TIL, or Today I Learned, is where our developers share the best tech stuff they found every day. You can find smart solutions for some issues, useful advice and anything which will make your developer life easier.

 

Photo by Andrew Neel on Unsplash

Code stories CTA
READ ALSO FROM Ruby/Ruby on Rails
Read also
Need a successful project?
Estimate project or contact us