How can I memoize a method that may return true or false in Ruby?
Posted
by
Seamus Abshere
on Stack Overflow
See other posts from Stack Overflow
or by Seamus Abshere
Published on 2012-06-22T15:09:30Z
Indexed on
2012/06/22
15:16 UTC
Read the original article
Hit count: 233
ruby
|memoization
Obviously ||=
won't work
def x?
@x_query ||= expensive_way_to_calculate_x
end
because if it turns out to be false
, then expensive_way_to_calculate_x
will get run over and over.
Currently the best way I know is to put the memoized true
or false
into an Array
:
def x?
return @x_query.first if @x_query.is_a?(Array)
@x_query = [expensive_way_to_calculate_x]
@x_query.first
end
Is there a more conventional or efficient way of doing this?
© Stack Overflow or respective owner