There is an idiom in ruby: x ||= y .
def something @something ||= calculate_something end private def calculate_something
But there is a problem with this idiom if your "long-running utility" can return a false value (false or nil), since the ||= operator will still evaluate the right side. If you expect false values, use an additional variable similar to that proposed by DigitalRoss:
def something return @something if @something_calculated @something = calculate_something @something_calculated = true return @something end
Do not try to save a line of code by setting the @something_calculated variable first and then running calculate_something. If the calculation function throws an exception, your function will always return zero and will never again call the calculation.
In general, Ruby uses instance variables. Please note, however, that they are visible in all methods of this object - they are not local to the method. If you need a variable shared by all instances, define a method in the class object and in each case call self.class.something
class User def self.something @something ||= calculate_something end def self.calculate_something # .... end def something self.class.something end end
source share