Can we use include statement to include a module anywhere within the class or does it has to be at the beginning of the class?
If I include the module at the beginning of my class declaration, method overriding works as expected. Why is it not working if i include at the end as described below?
# mym.rb
module Mym
def hello
puts "am in the module"
end
end
# myc.rb
class Myc
require 'mym'
def hello
puts "am in class"
end
include Mym
end
Myc.new.hello
=> am in class
When you include a module, its methods do NOT replace methods defined in this class, but rather they are injected into inheritance chain. So, when you call
super, method from included module will get called.They will behave almost the same way with other modules. When a module gets included, it is placed right above the class in inheritance chain, with existing modules placed above it. See example:
For more info see this post.
Also read this: http://rhg.rubyforge.org/chapter04.html