Ruby: Resumable functions with arguments

ruby

Solution

You probably want to encapsulate `inc_mult` into its own class, since you want to encapsulate its state separately from its containing object. This is how generators (the `yield` statement) work in Python and C#.

Something as simple as this would do it:

class Foo 
  state = 0 
  define_method(:[]) do |factor|
    state += 1
    factor * state
  end 
end

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.

Problem

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.)

Original source