How can I memoize a method that may return true or false in Ruby?
- by Seamus Abshere
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?