gpt4 book ai didi

ruby-on-rails - Ruby - 我们可以在类中的任何地方使用 include 语句吗?

转载 作者:数据小太阳 更新时间:2023-10-29 07:30:52 26 4
gpt4 key购买 nike

我们能否使用 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

最佳答案

当您包含一个模块时,它的方法不会替换此类中定义的方法,而是将它们注入(inject)到继承链中。因此,当您调用 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

关于ruby-on-rails - Ruby - 我们可以在类中的任何地方使用 include 语句吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8740790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com