On 15.01.2008 18:32, Andrew Stewart wrote:
> Hi Everyone,
> 
> I believe one can add methods to a class by including a module but  
> not override existing methods.  Indeed Dr Nic said as much here:
> 
> http://ruby.tie-rack.org/6/safely-overriding-method_missing-in-a- 
> class-that-already-has-it/#comment-7
> 
> Here's some code that demonstrates this.
> 
> class Foo
>    def answer
>      42
>    end
> end
> 
> module Bar
>    def answer
>      "What was the question?"
>    end
> 
>    def to_s
>      "bar"
>    end
> end
> 
> Foo.send :include, Bar
> f = Foo.new
> f.answer  # => 42, not "What was the question?"
> f.to_s    # => "bar", not "#<Foo:0x731248>"
> 
> 
> Why aren't existing methods overridden?  And where could I have  
> looked to find out the answer for myself (perhaps somewhere in Ruby's  
> source?)?

Because of the position in the inheritance hierarchy:

irb(main):001:0> module Bar;end
=> nil
irb(main):002:0> class Foo
irb(main):003:1> include Bar
irb(main):004:1> end
=> Foo
irb(main):005:0> Foo.ancestors
=> [Foo, Bar, Object, Kernel]

Methods defined in Foo are always found before their counterparts in 
included modules.  Consequently you can override super class methods 
with a module.

Kind regards

	robert