I usually use "one time assignment" (don't really know how to call this anw) in ruby like this:
class FooBar
def foo
@foo ||= begin
# Costly operation putting here
end
end
end
This will allow the variable @foo to be computed only once, then being used directly in subsequent calls to method foo. My question are:
- Is using
begin/endblock in this case good or not, as the documentation states that it is used for encapsulating exceptions, doesn't mention any other uses. - Can I use other block types (Proc, Lambda,
do/end) with this syntax? If yes then how?
initialize, but could be done anywhere. Yes,@foocould point to the result of any type of operation:@foo = arr.map...,@foo = if..else...end,@foo = lambda..., etc.