All Ruby on Rails Node JS Android iOS React Native Frontend Flutter QA

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
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!
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:

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
Need a successful project?
Estimate project