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
Written by Adam Stankiewicz
Related protips
1 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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Related Tags
#ruby
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#