From: 7stud -- Date: 2011-08-22T16:35:42+09:00 Subject: Re: Gritty Details of super() luke gruber wrote in post #1017749: > > hehe, if anyone is still reading this rambling stuff, I appreciate it. > I understood the issue you brought up in your first post. The following is an explanation of the issue. Suppose you have this hierarchy of classes: class Object def Object.meditate puts "Ohhhmmmmm" end end class Cat def Cat.species puts "Siamese" end def greet puts 'meow' end end class Dog < Cat end You can test out the hierarchy with this code: d = Dog.new d.greet #meow Dog.species #Siamese Dog.meditate #Ohhmm Here is what the method lookup looks like: '#' = singleton class Object -> #Object ^ ^ | | Cat --> #Cat ^ ^ | | Dog --> #Dog (methods called on Dog are looked up ^ in #Dog, #Cat, #Object) | d => #d (methods called on d are looked up in d#, Dog, Cat, Object) Now lets include a module in Dog: class Object def Object.meditate puts "Ohhhmmmmm" end end class Cat def Cat.species puts "Siamese" end def greet puts 'meow' end end module M def greet puts "Hi. I'm M." end end class Dog < Cat include M end Now we get different output for d.greet: d = Dog.new d.greet #Hi. I'm M Dog.species #Siamese Dog.meditate #Ohhmmm The typical explanation for that behavior is that the module M becomes an anonymous class that ruby inserts directly above Dog in the inheritance chain: '#' = singleton class Object -> #Object ^ ^ | | greet() Cat --> #Cat ^ | - greet() | M | - ^ ^ | | Dog --> #Dog ^ | d => #d So when ruby looks up greet() for d, it finds the greet() method in M before the greet() method in Cat. Now if the anonymous class (M) behaved like other classes in the inheritance chain, you would also expect this to happen: '#' = singleton class Object -> #Object ^ ^ | | Cat --> #Cat ^ ^ | | - | | M | -> #M - ^ ^ | | Dog --> #Dog ^ | d => #d But if you add a singleton method to M, you can verify that that doesn't happen: class Object def Object.meditate puts "Ohhhmmmmm" end end class Cat def Cat.species puts "Siamese" end def greet puts 'meow' end end module M def M.meditate puts "MMMMMMM" end def greet puts "Hi. I'm M." end end class Dog < Cat include M end Dog.meditate #Ohhhmmmmm The question is: Why isn't M's singleton class inserted into the singleton class hierarchy? People who are interested in such things, have probably read that including a module in a class does not include the singleton methods of the module in the class. What that means is, #M (= the singleton class, which contains the singleton methods) does not get inserted between #Dog and #Cat. As to why that is? I have no idea. -- Posted via http://www.ruby-forum.com/.