Forum: Ruby Singleton class - instance or class variables?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Caleb T. (Guest)
on 2005-12-20 03:14
(Received via mailing list)
When using a singleton class (one that includes Singleton, not an
eigenclass), can anyone think of any advantage/disadvantage to using
class variables over instance variables (or visa versa) to access
data in the class?

Thanks,
Caleb
Eero S. (Guest)
on 2005-12-20 04:03
Caleb T. wrote:
> When using a singleton class (one that includes Singleton, not an
> eigenclass), can anyone think of any advantage/disadvantage to using
> class variables over instance variables (or visa versa) to access
> data in the class?

I would recommend using class instance variables,
but the only reason I can think relates to resource
control and instance instantiation. For the typical
case one could just as well use classes and class
instance methods.

> Thanks,
> Caleb


E
Joel VanderWerf (Guest)
on 2005-12-20 04:20
(Received via mailing list)
Caleb T. wrote:
> When using a singleton class (one that includes Singleton, not an
> eigenclass), can anyone think of any advantage/disadvantage to using
> class variables over instance variables (or visa versa) to access  data
> in the class?

In answer to this question and the one about thread-specific singletons:
another approach to consider is using a dependency injection framework.
They all support singleton services, and at least some of them support
services that return one unique object per thread.

One disadvantage to using class variables (@@var) is that they are (in
the current ruby) per-hierarchy, not per class. So a subclass will share
the value of @@var. This is, I've heard, going to change in ruby 2.0.
unknown (Guest)
on 2005-12-20 04:50
(Received via mailing list)
On Tue, 20 Dec 2005, Caleb T. wrote:

> When using a singleton class (one that includes Singleton, not an
> eigenclass), can anyone think of any advantage/disadvantage to using class
> variables over instance variables (or visa versa) to access data in the
> class?

inheritence will break with either.

with @@var then

   class Singleton
     @@var = 42
   end

   class SingletonII < Singleton
     @@var = 'forty-two'
   end

   class Singleton
     p @@var #=> 'forty-two'
   end

but with @var

   class Singleton
     @var = 42
   end

   class SingletonII < Singleton
   end

   class SingletonII
     p @var #=> nil
   end

my traits lib solves this - if inheritence of class data is important.
it may
not be.

regards.

-a
This topic is locked and can not be replied to.