From: "Jesús Gabriel y Galán" Date: 2009-12-15T18:22:06+09:00 Subject: Re: does module have instance_methods? On Tue, Dec 15, 2009 at 5:25 AM, Ruby Newbee wrote: > I'm still confused, since module can't be instantiated, why it has the > instance methods? > > irb(main):162:0> module Mymod > irb(main):163:1>   def myway;end > irb(main):164:1> end > => nil > irb(main):165:0> Mymod.respond_to? :myway > => false > irb(main):166:0> Mymod.instance_methods > => [:myway] It has instance_methods because those methods will be called on an instance. It will not be an instance of that module, but it will be an object (an instance of some class). They are very similar to the instance_methods in a class, in the sense that an object at some point will have this module or class in the lookup path when you call a method on that instance, so that's the way an instance_method can be called. Look: irb(main):001:0> class A irb(main):002:1> def test irb(main):003:2> "test" irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> a = A.new => # irb(main):008:0> a.class.ancestors => [A, Object, Kernel] irb(main):009:0> a.test => "test" We can say a.test because A is in the lookup path of a's methods. The same happens with a module: irb(main):012:0> module Test irb(main):013:1> def test irb(main):014:2> "the module test" irb(main):015:2> end irb(main):016:1> end => nil irb(main):017:0> class A irb(main):018:1> include Test irb(main):019:1> end => A irb(main):020:0> a.class.ancestors => [A, Test, Object, Kernel] irb(main):011:0> a.test => "Test's test" As you can see, when class A includes the module, it appears in the lookup path of A, so its instances can call Test's instance methods. Let's do it in a different way now: irb(main):001:0> module Test irb(main):002:1> def test irb(main):003:2> "Test's test" irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> class A irb(main):007:1> def test irb(main):008:2> "A's test" irb(main):009:2> end irb(main):010:1> end => nil irb(main):011:0> a = A.new => # irb(main):012:0> a.extend Test => # irb(main):013:0> class << a; self; end.ancestors => [Test, A, Object, Kernel] irb(main):014:0> a.test => "Test's test" Instead of the class including the module, we extend just that instance with the module. If we check the lookup path of the singleton class of a, we can see that the module goes before the class, so in this case the module's method is called before the class one. Jesus.