nkm
nkm

Reputation: 5914

Ruby - Can we use include statement anywhere within the class?

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

Upvotes: 4

Views: 550

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

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:

module Mym
 def hello
  puts "am in the module"
 end
end

module Mym2
 def hello
  puts "am in the module2"
  super
 end
end

class Myc
 include Mym
 include Mym2

 def hello
   puts "im in a class"
   super
 end
end

puts Myc.new.hello
# im in a class
# am in the module2
# am in the module

For more info see this post.

Also read this: http://rhg.rubyforge.org/chapter04.html

Upvotes: 6

Related Questions