I use variable caching to cut down on execution time like so:
def some_method
return @var if @var
[some other code that gets executed only once]
end
Is there a shorthand for return @var if @var
? If its a single line method I use:
@var ||= [some more code]
Can something similar (short) be done with multiline methods?
In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).
Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it. If you wanted to explicitly return a value you can use the return keyword.
I use this:
@var ||= begin
# ...
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