Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you override a method by including a module? [duplicate]

Tags:

ruby

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"?

like image 681
farhadf Avatar asked Dec 17 '22 13:12

farhadf


1 Answers

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]
like image 139
Jörg W Mittag Avatar answered Jun 01 '23 07:06

Jörg W Mittag