Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
Memoization - this is when Ruby "remembers" the result of the calculation so as not to count again. Used for optimization - especially when the method is called many times.
How @x works ||= ...
@x ||= fetch_x
means:
If @x doesn't matter yet (ie nil or false), then execute fetch_x and save the result to @x. Otherwise, just return the already saved one.
Difference with simple assignment
@x = fetch_x # executes fetch_x EVERY time @x ||= fetch_x # only performs fetch_x FIRST time
For example:
def expensive puts "Calculating..." 42 end def answer @answer ||= expensive end answer # => Calculating... 42 answer # => 42 (no calculation for the second time!)
But careful:
||= will not work if the value can be false:
@flag ||= true # if @flag = false, Ruby will consider it "empty" and rewrite it to true
If you need to save even false, it is better to write:
@flag = true if @flag.nil?
This post doesn't have any additions from the author yet.