From: Rick DeNatale Date: 2007-12-13T23:33:39+09:00 Subject: Re: Inheritance and meta-classes On 12/13/07, Robert Klemme wrote: > > > How do I find where a function is defined in the inheritance tree? > > > Because of metaclass inheritance being cyclical I don't know where > > > to stop looking. > > Where exactly do you see cycles? I am not aware of any. shadowfax:~/ssanta rick$ irb irb(main):001:0> def meta irb(main):002:1> class << self irb(main):003:2> self irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> meta => #> irb(main):007:0> Array.meta => # irb(main):008:0> Array.meta.superclass => # irb(main):009:0> Array.meta.superclass.superclass => # > 2007/12/13, Adam Salter : > > I still don't get how you can query and see where in the chain a > > method got added to an object... > > > > I've now found that you can do: > > obj.class.ancestors # => Array > > > > But that still doesn't include metaclasses... > > Correct. > > > How does Ruby know?? > > The meta class is there but it's hidden from #ancestors as you found > out. Inheritance wise it sits between an object and its class. > > irb(main):001:0> c1 = Class.new > => # > irb(main):002:0> def c1.x; "X" end > => nil > irb(main):003:0> c1.x > => "X" > irb(main):004:0> c2 = Class.new c1 > => # > irb(main):005:0> c2.x > => "X" > irb(main):006:0> c2.ancestors > => [#, #, Object, Kernel] > irb(main):007:0> c1.class.instance_methods.grep /x/ > => ["extend"] > irb(main):008:0> class < => ["x", "extend"] I don't see any metaclasses here. c1 and c2 are simply anonymous classes. A metaclass doesn't sit between an instance and its class. A singleton class of an instance would, but that's not a metaclass (although the way the two terms get conflated I can see where that's a common misconception). A metaclass is a singleton 'class' which holds the behavior of a class. Here's a simplified diagram http://myskitch.com/rubyredrick/skitched-20071213-093049/ It's simplified since it doesn't include the inclusion of Kernel by Object. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/