On Tue, Oct 15, 2013 at 7:29 AM, Love U Ruby [email protected]
wrote:
class D
include M
end
D.new.foo # => “12”
Yes,as per the above example and you,it seems to me that,Module instance
methods became class methods of Class.
No. By extending any object with a module instance methods defined
in the module become methods of the object - even if that object is a
class as in your case. That means, they are inserted in the
inheritance hierarchy of the singleton class:
irb(main):001:0> module F
irb(main):002:1> def foo; 123 end
irb(main):003:1> end
=> nil
irb(main):004:0> o = Object.new.extend F
=> #Object:0x0000060003db98
irb(main):005:0> o.singleton_class.ancestors
=> [F, Object, Kernel, BasicObject]
Do not confuse Class with “a class”. Class is the class of any class:
irb(main):010:0>
ObjectSpace.each_object(Class).each_with_object(Hash.new(0)) {|c,h|
h[c.class] += 1}
=> {Class=>407}
In my example
class C;end
C is an instance of Class. Then C.ancestors should throw error.
Why?
I am missing the connection…
Yes, it seems so. You need to be aware that there is a (or at least
one, depending how you look at it) cycle in Ruby’s class hierarchy.
Some lines as food for thought
irb(main):011:0> Object.ancestors
=> [Object, Kernel, BasicObject]
irb(main):012:0> Object.class.ancestors
=> [Class, Module, Object, Kernel, BasicObject]
irb(main):013:0> Class.ancestors
=> [Class, Module, Object, Kernel, BasicObject]
irb(main):014:0> BasicObject.class
=> Class
irb(main):015:0> Class.class.ancestors
=> [Class, Module, Object, Kernel, BasicObject]
irb(main):016:0> Class.class
=> Class
Note line 16.
Cheers
robert