From: Hugh Sasse Date: 2005-11-17T01:27:43+09:00 Subject: Re: static variable; behaviour in ruby? On Thu, 17 Nov 2005, Robert Klemme wrote: > Hugh Sasse wrote: > > On Thu, 17 Nov 2005, Robert Klemme wrote: > > > >> Let's see whether I understand this correctly: you want your method > >> "within" to create something that can be later thrown against the > >> current line of the input and execute the given block only if the > >> condition matches? Wouldn't it be easier to just call within for > >> each line of the input? > > > > all the statements in the input language which I'm processing with > > instance_eval (for now) would be called for each line of the input. > > So when each one that must hold state is called for the first time > > it must clear the state, for future calls to that function on that > > source line, but later input lines, it must not "cold start" the > > state. My use of "input" for supplied source code *and* data to process was less than helpful. Sorry about that. > > > > For within(), I'm trying to model sed's '/this/, /that/ { do_this}' > > And I could have several withins in the same chunk of input > > language. > > I think I start getting a better understanding of your issue. How about: > > def within(*a, &b) > my_state = (Thread.current[:within] || = {})[a] ||= WithinState.new(a,b) > my_state.feed(current_line) > end > > If you want to make this safe against multiple invocations with similar > parameters you might use another identifying thing (possibly invoking > caller to determine source code location). Yes, I was looking for that: I'd forgotten I could use caller in something eval'd. Making it thread local means it outlives the scope of def and is not in the normal global namespace. That's a neat idea. I think this will do everything I want.... > > Instead of the thread local you could also use a global but IMHO this is > cleaner. > > HTH > > Kind regards > > robert > Thank you, Hugh > >