From: David Masover Date: 2009-11-28T07:24:43+09:00 Subject: Re: Class variables, instance variables, singleton; Ruby v. C++ On Friday 27 November 2009 01:07:45 pm Ralph Shnelvar wrote: > Newb here coming from C++ > > Ok, I _think_ I know what a class variable is. It is similar to a > static variable in a class in C++. Rght? Yes. A quick warning, though: Class variables behave weirdly with inheritance. Avoid them. Since all Ruby classes are themselves objects, it makes more sense to define an instance variable of the class. That is, instead of doing this: class Foo def bar @@some_count += 1 end end Do this: class Foo def self.increment_count @some_count += 1 end def bar self.class.increment_count end end If you understand how that works, you should be able to understand this example, which is how I'd actually do it: class Foo class << self attr_accessor :some_count end def bar self.class.some_count += 1 end end I'm sure there's a library somewhere that deals with these more easily. > An instance variable is apart of an instantiated class, right? > > What's a singleton? I don't think it's the same as as singleton in > C++ parlance. It probably is, but you never know... There is actually a Singleton module in the standard library. The idea is to prevent you from creating more than one instance of a given class. There's also the idea of singleton methods -- for example, you can take two objects of a given class, and define a method on one of them, without making a new class. Try this in irb: a = 'foo' b = 'bar' def a.speak puts self end a.class == b.class a.speak b.speak This is, by the way, why we don't tend to care what class an object is, but rather, how it behaves -- because in Ruby, duck typing is the only kind of typing that makes sense, since you really can't know how an object will behave just by looking at its class. > If Class X wants to access a class variable and/or constant in Class Y, > must a class method be defined or is there a direct way to do it? Marnen is mostly right. There actually is a way -- class_variable_get -- but that's cumbersome, and you shouldn't use it unless you know what you're doing. And again, if you're already going to define a class variable, you might consider using an instance variable on the class.