Strange bit of code

I came across an unusual behavior of remove_method the other day. When I discovered that it didn't work as I expected I experimented until I found a relatively simple example illustrating what happens. The show method doesn't seem to be removed when the example calls remove_method, but it is removed as soon as a show method is defined in any module or class, even if is defined in a module or class not related in any way to the module it is removed from. Can anyone explain why this works the way it does?

Thanks,
Matthew

module A
   module B
     def show
       "pr"
     end
   end
end
class C
   include A::B
end

p "normal: " << C.new.show

p C.instance_methods - C.superclass.instance_methods
p A::B.instance_methods
module A
   module B
     remove_method :show
   end
end
p C.instance_methods - C.superclass.instance_methods
p A::B.instance_methods

p "shouldn't work - pr was removed " << C.new.show

module A
end

p "still shouldn't work " << C.new.show

module S
   def show
   end
end
# the next line throws an error
p "defining a show method in any class or module now causes it to stop working " << C.new.show

Hi,

At Wed, 16 Aug 2006 12:58:57 +0900,
Matthew Johnson wrote in [ruby-talk:208741]:

I came across an unusual behavior of remove_method the other day.
When I discovered that it didn't work as I expected I experimented
until I found a relatively simple example illustrating what happens.
The show method doesn't seem to be removed when the example calls
remove_method, but it is removed as soon as a show method is defined
in any module or class, even if is defined in a module or class not
related in any way to the module it is removed from. Can anyone
explain why this works the way it does?

I think it's a fixed bug. Can you try it with latest snapshot?

$ grep -C2 rb_clear_cache ChangeLog

···

Mon Jul 10 09:29:12 2006 Nobuyoshi Nakada <nobu@ruby-lang.org>

  * eval.c (rb_clear_cache_for_undef): clear entries for included
    module. fixed: [ruby-core:08180]

--
Nobu Nakada

I think it's a fixed bug. Can you try it with latest snapshot?

$ grep -C2 rb_clear_cache ChangeLog

  * eval.c (rb_clear_cache_for_undef): clear entries for included
    module. fixed: [ruby-core:08180]

-- Nobu Nakada

Thanks! That does look like the source of it. It makes much more sense now... :slight_smile:

Matthew

···

Mon Jul 10 09:29:12 2006 Nobuyoshi Nakada <nobu@ruby-lang.org>