2dia7q
Last Updated: February 25, 2016
·
684
· sheerun
Photo on 08.01.2013 at 04.15

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
Say Thanks
Respond

1 Response
Add your response

26320
23e4fc3add5443f51e55663cfc245d24

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 ·
Awesome Job

0dbe43fc 55f1 11e7 9f7e e393aaf472a4
Web Developer
·
Long Beach, CA
·
Full Time