On Sep 22, 2005, at 8:31 PM, jdm wrote:

> i'm trying to create what C calls a static local variable inside a  
> particular
> method, i.e. this variable should not be visible outside the method  
> and its
> value should survive the activation of the method.
>
> instance variables are "static" but visible to all methods of the  
> instance.
>
> local variables are visible only to a particular method but aren't  
> "static".
>
> i've been through the pickaxe book and nothing obvious popped out  
> at me. it
> seems i could synthesize the desired functionality using singleton  
> methods
> attached to a particular instance (or maybe by defining a block  
> within the
> method) but i'm hoping there's a simpler, cleaner way.
>
> thanx in advance.
>
>
>
>

Closures are your friends

% cat a.rb
class A
     def meth1
            puts "I'm meth1"
      end
      def meth2
           puts "I'm meth2. I try to access something I ain't  
allowed: #{static_var}"
      end
       class_eval do
             static_var = 3
             define_method(:meth3) do
                      puts "I'm meth3. I'm allowed to access # 
{static_var}"
             end
       end
end

a = A.new
a.meth1
a.meth3
a.meth2

% ruby a.rb
I'm meth1
I'm meth3. I'm allowed to access 3
a.rb:6:in `meth2': undefined local variable or method `static_var'  
for #<A:0x26148> (NameError)
         from a.rb:19


Personally I think C's static vars are cheesy attempt to provide the  
a tiny amount of the power of lexicaly scoped closures in a language  
with manual memory management.

In this case I don't know if a variable with this kind of scope is  
the best choice however, are you sure you can't make the method into  
an object?