【问题标题】:Ruby - Can we use include statement anywhere within the class?Ruby - 我们可以在类中的任何地方使用 include 语句吗?
【发布时间】:2012-01-05 10:16:51
【问题描述】:

我们可以使用include 语句在类中的任何位置包含一个模块还是必须在类的开头?

如果我在类声明的开头包含模块,方法覆盖将按预期工作。如果我在末尾包含如下所述,为什么它不起作用?

# 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

【问题讨论】:

    标签: ruby-on-rails ruby oop


    【解决方案1】:

    当你包含一个模块时,它的方法不会替换这个类中定义的方法,而是将它们注入到继承链中。因此,当您调用super 时,将调用包含模块中的方法。

    它们与其他模块的行为方式几乎相同。当一个模块被包含时,它被放置在继承链中类的正上方,现有模块放在它上面。见例子:

    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
    

    欲了解更多信息,请参阅this post

    另请阅读:http://rhg.rubyforge.org/chapter04.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      相关资源
      最近更新 更多