From: Robert Klemme Date: 2005-11-17T00:03:08+09:00 Subject: Re: static variable; behaviour in ruby? Hugh Sasse wrote: > On Wed, 16 Nov 2005, Brian Schr�der wrote: > >> On 16/11/05, Hugh Sasse wrote: >>> Any idea how to create or simulate a static variable in ruby? >>> >>> I want to create a variable to hold state between calls of a method, >>> but have the state disappear when the method goes out of scope. >>> I could create it in some external object but then I'd need to query >>> the scoping rules, and know where i was. >>> >>> I'm trying to do an instance_eval on a string containing a method >>> such as do_this x,y,z {block} >>> and I want to evaluate the block, or not, as a function of some >>> state against which x,y,z are compared. The code will be called >>> several times, but I only want the state intialized the first time >>> the scope >>> is entered. >>> >>> And, just to make matters worse, there could be several independent >>> calls to this method within the scope, each with its own separate >>> state. >>> >>> Maybe there's another way to do this? >>> >>> Thank you >>> Hugh >>> >>> >> >> I advise that you state your basic problem, as this seems to be a >> problem with an ugly workaround. You can probably restructure your >> problem such that this is no longer needed. > > I thought the paragraph about instance_eval explained it :-). > > Essentially, I have become fed up with lousy diagnostics from sed, > and have been trying to re-implement (enough of) it in Ruby, so I > hae some chance of getting the code to work. Thus I'd use code like: > > within 10, 30 { > sub(/this/, 'that') > sub(/thingy/, 'the other') > # Example of munging something akin to C comments > within /^\s+\/\*/, /\*\/\s*$/ { > rot13 # or something > } > } > > So I need to keep track of which patterns have matched, and clear > them when the scope (surrounding block) is gone. 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? Kind regards robert