dblack / wobblini.net wrote: > 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) > The visibility issue is quite confusing. See the following example. X = "top-level" class C X = "class-level" class << self def a puts X end end end def C.b puts X end class << C def c puts X end end C.a #=>class-level C.b #=>top-level C.c #=>top-level class D X = "class-level" def f puts X end end obj = D.new def obj.g puts X end class << obj def h puts X end end obj.f #=>class-level obj.g #=>top-level obj.h #=>class-level Very inconsistent between a class and an object. Can somebody explain this strange behavior? Thanks. Sam