Last Updated: February 25, 2016
·
913
· sheerun

Beware ||= operator when dealing with booleans

You can use ||= operator for caching variables:

def pi
  @pi ||= Pi.compute_precisely
end

Just watch out when dealing with booleans, especially if the result of function is time-dependent or nondeterministic:

def schrodingers_cat_dead?
  @dead ||= rand < 0.5
end

schrodingers_cat_dead? # => false
schrodingers_cat_dead? # => false
schrodingers_cat_dead? # => true

In this case @dead caching variable is evaluated until it become true. That's because !!nil == false. Instead you should write:

def schrodingers_cat_dead?
  @dead = rand < 0.5 if @dead.nil?
  @dead
end

schrodingers_cat_dead? # => false
schrodingers_cat_dead? # => false
schrodingers_cat_dead? # => false

1 Response
Add your response

I'd recommend this form:

def foo
  return @cache if defined? @cache
  @cache = some_expensive_operation
end

This even handles scenarios when some_expensive_operation validly returns nil

over 1 year ago ·