On 7/24/07, Marcin Tyman <m.tyman / interia.pl> wrote:
> Hi everybody,
> Is any way to define static variables over function? As class static
> variables there is possible to define a static class variable as
> @@name_of_var. But I'm not sure if Ruby let define such variables in
> functions (like in C/C++)
>
> Thanks in advance,
> MT
> --
> Posted via http://www.ruby-forum.com/.
>
There are three kinds of variables in Ruby
local
@@class_var
@instance_var

My tip, do not use @@class_var, use @inst_var on the correct level

Here goes the classic example of a "static" (forget this expression;)
variable counting instances.
I will use an instance variable of the class (commonly called class
instance variables) for that

549/49 > cat class-inst.rb && ruby class-inst.rb

class A
        @count = 0
        class << self
                attr_accessor :count
        end
        def initialize val
                @a = val
                self.class.count += 1
        end
end

a=A.new 42
b=A.new 43

p a
p b
p A.count
#<A:0xb7db6764 @a=42>
#<A:0xb7db66b0 @a=43>
2
HTH
Robert

-- 
I always knew that one day Smalltalk would replace Java.
I just didn't know it would be called Ruby
-- Kent Beck