class Example
def foo
def foo
@bar
end
bar = (1..10).inject(1, :*)
puts "bar is #{bar}"
@wibble = "wibble is #{bar / 30}"
@bar = bar / 20
end
end
example = Example.new
example.foo
bar is 3628800
=> 181440
example.foo
=> 181440
The hard working method, the outer def foo
is called only once, on the first invocation, afterward, the nested def foo
overrides it and simply returning the @bar
variable from the object. The nested def foo
still accessing the same object.
Note that rubcop will yell at you with this memozation pattern.