Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
Memoization is when Ruby "remembers" the result of a computation so it doesn't have to calculate it again. It is used for optimization - especially when the method is called many times.
How @x ||= ... works
@x ||= fetch_x
means:
If @x does not have a value yet (i.e., nil or false), then execute fetch_x and store the result in @x. Otherwise, just return the already stored value.
Difference from simple assignment
@x = fetch_x # executes fetch_x EVERY time @x ||= fetch_x # executes fetch_x only the FIRST time
For example:
def expensive puts "Calculating..." 42 end def answer @answer ||= expensive end answer # => Calculating... 42 answer # => 42 (without recalculating!)
But be careful:
||= will not work if the value can be false:
@flag ||= true # if @flag = false, Ruby will consider this "empty" and overwrite it with true
If you need to keep even false, it's better to write:
@flag = true if @flag.nil?
This post doesn't have any additions from the author yet.