Gary Wright
1/25/2007 5:17:00 AM
On Jan 24, 2007, at 8:05 PM, Sebastian wrote:
> uuh-ooh. i guess i could use an instance variable for the Singleton
> class instead :)
>
>> def greeting
>> @greeting ||= self.determine_greeting
>> end
That isn't an instance variable for the singleton class. It is an
instance variable associated with the class itself. The singleton
class for an object acts as a container for method definitions but
it is the object itself that has the instance variables.
> It seems to have the exact same effect than a class variable
> defined in the class. Is this correct?
There are various differences but the biggest is that a class
instance variable, just like all instance variables, is only
accessible via the individual class object and not through any
subclasses as would be the case with a class variable.
Most Ruby veterans seem to shun Ruby class variables in favor of
class instance variables. Despite the name, Ruby class variables
are not like class variables in other object oriented languages.
Almost always a 'class instance variable' is a better choice.
Gary Wright