From: Dan Doel Date: 2003-08-22T13:34:22+09:00 Subject: Re: Class variables - a surprising result Patrick Bennett wrote: > Ryan Pavlik wrote: > >> Basically, in Ruby, you _do_ have what C++/Java would call a "static >> class member", and you also have something else---@@class variables. >> It's mostly the term here that's confusing, I think. >> > No, @variables are like normal instance variables in C++. They > *definitely* aren't like C++ 'static's. @@variables aren't like C++ > statics either, but that's not necessarily a *bad* thing - it's > just... different ;) @variables are only like C++ instance variables when used within instance methods. If you do: class Foo @var = 6 def Foo.print p @var end def print p @var end end Then: Foo.print # => 6 Foo.new.print # => nil If you want to access these in instance methods, you need to do: class Foo def instance_meth p self.class.class_eval { @var } end end You cannot do: class Foo def instance_meth p class << self; @var; end end end Because @var is an instance variable in the Foo class object, not in the singleton class object of an instance of Foo (or maybe there's some other explanation I can't come up with). So it is effectively a class instance variable, although that's still not the same as a Java static variable, since it's not inherited. - Dan