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#include
mixes in the module as the direct superclass of whatever class it is being mixed into. M
is a superclass of Foo
, so Foo#bar
overrides M#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 override Foo#bar
in a subclass of Foo
.
You can clearly see the ancestry:
class FooS; end
module M; end
class Foo < FooS; include M end
Foo.ancestors # => [Foo, M, FooS, Object, Kernel, BasicObject]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With