Ruby - Can I use an include statement inside a class?

Can I use the include statement to include a module anywhere in the class, or should it be at the beginning of the class?

If I include the module at the beginning of the class declaration, the method override works as expected. Why doesn't it work 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 
+4
source share
1 answer

When you include a module, its methods DO NOT replace the methods defined in this class, but rather are introduced into the inheritance chain. Thus, when calling super , the method from the included module is called.

They will behave almost the same as with other modules. When a module is turned on, it is placed directly above the class in the inheritance chain with the modules existing above it. 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 

See this post for more details.

Also read the following: http://rhg.rubyforge.org/chapter04.html

+5
source

Source: https://habr.com/ru/post/1389429/


All Articles