A
Andrew Stewart
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?)?
Thanks and regards,
Andy
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?)?
Thanks and regards,
Andy