From: "David A. Black" Date: 2009-09-14T03:44:10+09:00 Subject: Re: module to overwrite method defined via define_method Hi -- On Mon, 14 Sep 2009, 7stud -- wrote: > But what about here: > > module Redef > def foo > puts "'foo' from module" > end > end > > class A > define_method("foo") do > puts "'foo' from define_method" > end > > def initialize > class << self > include Redef > end > end > > include Redef #<---*****CHANGE HERE > > end > > p A.ancestors > a = A.new > a.foo > > > I would expect the order of the look up for the foo method to be: > > a's singleton class ==> 'foo from module' > a's class(=A) ==> 'foo from define method' > a's mixins(=Redef) ==> 'foo from module' > > > But the output is: > > [A, Redef, Object, Kernel] > 'foo' from define_method I believe what's happening is this: when you include Redef in a's singleton class, Ruby sees that it's already in the ancestors (since it's been included in A) and doesn't add it. In this example, I've got one module that's included in A, and one isn't, and I extend my instance with both. As you can see, the Dummy module appears before A in the ancestor list for a's singleton class, whereas Redef doesn't. module Redef def foo puts "'foo' from module" end end module Dummy end class A def foo puts "'foo' from A" end def initialize extend(Redef) extend(Dummy) end include Redef end a = A.new a.foo p A.ancestors class << a; p ancestors; end Output: 'foo' from A [A, Redef, Object, Kernel] [Dummy, A, Redef, Object, Kernel] David -- David A. Black, Director Ruby Power and Light, LLC (http://www.rubypal.com) Ruby/Rails training, consulting, mentoring, code review Book: The Well-Grounded Rubyist (http://www.manning.com/black2)