From: dblack@... Date: 2006-03-02T23:07:08+09:00 Subject: Re: Class method in singleton_methods? Hi -- On Thu, 2 Mar 2006, Minkoo Seo wrote: > Hi group. > > I've found that I have to query class methods like: > > irb(main):001:0> class Foo > irb(main):002:1> def Foo.bar > irb(main):003:2> end > irb(main):004:1> end > => nil > irb(main):005:0> Foo.singleton_methods > => ["bar"] > irb(main):006:0> > > It is interesting that a class method is actually a singleton method. I > know that there are tons of posting regarding metaclasses/objects. > Unfortunately, there are simply too many to read and understand all of > them. So, please forgive my naive question. > > Here's the thing. I guess Foo is actually defined like: > > irb(main):001:0> Foo = Class.new > => Foo > irb(main):002:0> class << Foo > irb(main):003:1> def Foo.bar > irb(main):004:2> end > irb(main):005:1> end > => nil > irb(main):006:0> Foo.singleton_methods > => ["bar"] > irb(main):007:0> > > Am I correct? A class method is indeed a singleton method of a Class object. The term "class method" is really just a convenient label for this case, because it occurs quite frequently. The "def obj.meth" and "class << obj; def meth" techniques differ as to the visibility of constants: X = 1 class C X = 2 def self.a puts X end end class << C def b puts X end end C.a # 2 (C::X) C.b # 1 (top-level X) But in the vast majority of cases you can use them pretty much interchangeably. David -- David A. Black (dblack@wobblini.net) Ruby Power and Light (http://www.rubypowerandlight.com) "Ruby for Rails" chapters now available from Manning Early Access Program! http://www.manning.com/books/black