I want a function that keeps local state in Ruby. Each time I call the function I want to return a result that depends both on a calling argument and on the function’s stored state. Here’s a simple example:
def inc_mult(factor)
@state ||= 0 # initialize the state the first time.
@state += 1 # adjust the internal state.
factor * @state
end
Note that the state is initialized the first time, but subsequent calls access stored state. This is good, except that @state leaks into the surrounding context, which I don’t want.
What is the most elegant way of rewriting this so that @state doesn’t leak?
(Note: My actual example is much more
complicated, and initializing the
state is expensive.)
You probably want to encapsulate
inc_multinto its own class, since you want to encapsulate its state separately from its containing object. This is how generators (theyieldstatement) work in Python and C#.Something as simple as this would do it:
Philosophically, I think what you’re aiming for is incompatible with Ruby’s view of methods as messages, rather than as functions that can somewhat stand alone.