The rules says:
A ||= B assigns B to A only if A is nil or falseSo, 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 endbut 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! endJust 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:
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.