From: Rick DeNatale Date: 2006-10-27T23:06:10+09:00 Subject: Re: Singleton Methods On 10/27/06, Max Lapshin wrote: > > On Oct 27, 2006, at 10:15 AM, bparanj@gmail.com wrote: > > > What is the purpose of singleton method? Why is singleton method > > defined on individual object instead of a class? TIA > > > > > > You call Article.new. new is the singleton method of object Article. > It is not "class method", there is no such thing in Ruby. There is > singleton method of object Article Not really. irb(main):001:0> class Article irb(main):002:1> end => nil irb(main):003:0> Article.method(:new) => # new is an instance method of Class. irb(main):004:0> Class.instance_methods.include?("new") => true Article (or any Class object) is an instance of Class and gets the new method by normal inheritance. irb(main):005:0> Article.class => Class irb(main):006:0> Article.method(:new) => # Each class object does have a singleton class where any class methods live. irb(main):008:0> Article.singleton_methods => [] irb(main):009:0> class Article irb(main):010:1> def self.foo irb(main):011:2> end irb(main):012:1> end => nil irb(main):013:0> Article.singleton_methods => ["foo"] Ruby uses singleton classes of classes instead of explicit metaclasses, but unlike "normal" singleton classes, singleton classes of classes get shared with subclasses irb(main):014:0> class JournalArticle < Article irb(main):015:1> end => nil irb(main):016:0> JournalArticle.singleton_methods => ["foo"] irb(main):017:0> The class and singleton class of class hierarchies parallel each other. irb(main):017:0> Article.instance_of?(Class) => true irb(main):018:0> Article.class.instance_of?(Class.class) => true irb(main):019:0> JournalArticle.class.instance_of?(Article.class) => true irb(main):020:0> JournalArticle.class.instance_of?(Class.class) => true In general, you can't subclass 'normal' singleton classes. The ruby implementation does this for singleton classes of classes 'under the covers.' irb(main):021:0> a = "foo" => "foo" irb(main):022:0> def a.singleton_method irb(main):023:1> "Oh sole mio!" irb(main):024:1> end => nil irb(main):025:0> aclass = class << a; self;end => #> irb(main):026:0> class B < aclass irb(main):027:1> end TypeError: can't make subclass of virtual class from (irb):26 This double use of singleton classes can be confusing to some who think that the 'singleton' in 'singleton class' means that it's not shared with any other object. Of course all this has probably gotten a tad deep for the context of the OPs question. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/