From: Jamis Buck Date: 2004-11-05T01:26:03+09:00 Subject: Re: class variable and singleton 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'. > Which one is better and why? > Can someone explain it, please. > > Thanks in advance... :-) It is difficult (though not impossible) to do initialization code on a class. For instance, with the Singleton include, you can have a constructor that does one-time initialization on the instance: class Foo include Singleton def initialize ... end end f = Foo.instance To do the same thing with a class-based singleton would require you to do some less-intuitive initialization magic. - Jamis -- Jamis Buck jgb3@email.byu.edu http://www.jamisbuck.org/jamis