TIL #5: How to work with Conditional Assignment Operator

Photo of Marcin Brzeziński

Marcin Brzeziński

Apr 3, 2018 • 2 min read
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

Photo of Marcin Brzeziński

More posts by this author

Marcin Brzeziński

A perpetually smiling & cheerful guy! For as long as he can remember, computer has been his hobby,...
How to build products fast?  We've just answered the question in our Digital Acceleration Editorial  Sign up to get access

We're Netguru!

At Netguru we specialize in designing, building, shipping and scaling beautiful, usable products with blazing-fast efficiency
Let's talk business!

Trusted by:

  • Vector-5
  • Babbel logo
  • Merc logo
  • Ikea logo
  • Volkswagen logo
  • UBS_Home