From: "David A. Black" Date: 2004-11-05T02:56:12+09:00 Subject: Re: class variable and singleton Hi -- On Fri, 5 Nov 2004, Mohammad Khan wrote: > consider the following two classes: > > class Foo1 > attr_accessor :data > include Singleton > end > > class Foo2 > def data > return @@data > end > > def data=(val) > @@data = val > end > end > > in irb screen: > > [mkhan@localhost mkhan]$ irb > irb(main):001:0> require 'singleton' > => true > irb(main):002:0> class Foo1 > irb(main):003:1> attr_accessor :value > irb(main):004:1> include Singleton > irb(main):005:1> end > => Foo1 > irb(main):006:0> a = Foo1.instance > => # > irb(main):007:0> b = Foo1.instance > => # > irb(main):009:0> a.value = 100 > => 100 > irb(main):010:0> p b.value > 100 > => nil > irb(main):011:0> class Foo2 > irb(main):012:1> def value > irb(main):013:2> return @@value > irb(main):014:2> end > irb(main):015:1> def value=(val) > irb(main):016:2> @@value = val > irb(main):017:2> end > irb(main):018:1> end > => nil > irb(main):019:0> a = Foo2.new > => # > irb(main):020:0> b = Foo2.new > => # > irb(main):022:0> a.value = 100 > => 100 > irb(main):023:0> p b.value > 100 > => nil > > in both class we will have single instance of 'data'. Do you mean 'value' rather than 'data'? > Which one is better and why? > Can someone explain it, please. I think you'd probably make the decision to use Singleton based primarily on the question of whether you really need the "only one instance" thing. If you just need a way to maintain state in a class that doesn't mix in Singleton, you have several choices: 1. a class variable. At the moment (Ruby 1.8), class variables are not strictly class-scoped; they are shared by subclasses. This is scheduled to change, so that they are truly class-scoped. 2. an instance variable of the class. This is really the purest way to do it, I think. What you're doing is basically allowing the Class object to behave like a regular Ruby object -- which it is. The downside is that it can be mildly awkward to set up accessor methods, should you want them: class C def C.var; @var; end def C.var=(x); @var = x; end end or class C class << self attr_accessor :var end end Then you can do: class C def some_method x = self.class.var # etc. end end 3. Maybe a constant or class method would be sufficient -- or maybe not, but I thought I'd list them too :-) David -- David A. Black dblack@wobblini.net