I find myself doing the following a lot to define return values from ruby methods:
def foo
val = (some expression)
val
end
This always seems a bit contrived. What's the best practice here?
It is unnecessary to save it to a variable unless (some expression) is heavy and will be called multiple times. In that case you might want to cache it.
I would go with either:
def foo
(some expression)
end
or for caching:
def foo
@val ||= (some expression)
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