Possible Duplicate:
Overriding method by another defined in module
Here’s some code:
class Foo
def bar
puts "Original bar"
end
end
module M
def bar
puts "Called M::bar"
end
end
Foo.send(:include,M)
Foo.new.bar
# => Original bar
Does ruby prevent overriding a previously defined method when a method of the same name is “included”?
I don’t quite understand your question. What, exactly, do you think is “prevented” here, and by whom?
This is precisely how it is supposed to work.
Module#includemixes in the module as the direct superclass of whatever class it is being mixed into.Mis a superclass ofFoo, soFoo#baroverridesM#bar, because that’s how inheritance works: subclasses override superclasses, not the other way around. Nothing is being “prevented” here, of course you can still overrideFoo#barin a subclass ofFoo.You can clearly see the ancestry: