In Python I can easily decorate methods so that they remember their result:
def store(self):
a = line1()
b = line2(a)
return line3(b)
=>
from lazy import lazy
@lazy
def store(self):
a = line1()
b = line2(a)
return line3(b)
Is there some similar idiom in Ruby for calculating method result only once?
In Ruby this is generally called memoization and it takes the naive form of:
def store
@store ||= begin
a = line1
b = line2(a)
line3(b)
end
end
There are important concerns if this code is used in a multi-threaded environment, though, which is why there are gems that manage this and ensure your lazy initializers are run only once if that's a concern.
Another option that works with false
and nil
too:
def store
unless defined?(@store)
a = line1
b = line2(a)
@store = line3(b)
end
@store
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With