0

When I have a code that transits through finite states for arbitrary many times as in the following example,

def a
  ...
  case some_condition
  when :foo then a
  when :bar then b
  else           c
  end
end
def b
  ...
  case some_other_condition
  when :baz then  a
  when :bang then b
  else            c
  end
end
def c
  ...
  case still_another_condition
  when :zap then  a
  when :boom then b
  else            c
  end
end
a

I think that the call stack will grow every time there is a transition to the new state, and that will cause a performance issue. Is there a way to avoid arbitrary growth of the call stack? Is tail recursion optimization related to this?

sawa
  • 165,429
  • 45
  • 277
  • 381
  • What's your use case for this? It may be helpful in devising a good solution. – Andrew Marshall Sep 26 '12 at 05:52
  • @AndrewMarshall Condition is mainly driven by the user input (via `gets`), and the next state is decided according to that and the present state. – sawa Sep 26 '12 at 05:55

1 Answers1

2

The first solution that comes into my mind is some kind of routing method:

def routing(call = :a)
  begin
    call = send call
  end until call == :end
end

Then the other methods just return the name of the method to call next:

def a
  ...
  case some_condition
  when foo then :a
  when bar then :b
  else          :c
  end
end

This will keep the call stack flat. When you want to skip the routing loop, return :end.

Clemens Helm
  • 3,841
  • 1
  • 22
  • 13
  • This looks very good. I will wait for a while to see if there are other possible answers. – sawa Sep 26 '12 at 06:07