我学习红宝石,我想出了一些我不了解的东西。我知道ruby中的模块用于命名空间与 :: (或。)并与 include 指令混合使用。 当我将一些方法组合在一个模块中而不将它们放在一个类中时,就会出现问题。 这是一个例子:
module Familiar
#this will not work
def ask_age
return "How old are you?"
end
#this will work
def Familiar::greeting
return "What's up?"
end
end
# this call returns **NoMethodError**
puts(Familiar::ask_age())
# this call works fine
puts(Familiar::greeting())
为什么我需要包含命名空间来定义方法,我已经在命名空间内熟悉为什么我必须重复我的自我并放置熟悉::问候语 您可以通过以下链接在线测试我的示例:http://codepad.org/VUgCVPXN
答案 0 :(得分:26)
Ruby documentation on Module在其简介文本中回答了这一点。
此表格:
module Familiar
def ask_age
return "How old are you?"
end
end
将#ask_age
定义为Familiar上的实例方法。但是,您无法实例化模块,因此无法直接访问其实例方法;你把它们混合到其他类中。模块中的实例方法或多或少是无法直接访问的。
此表格相比较:
module Familiar
def self.ask_age
return "What's up?"
end
end
将::ask_age
定义为模块函数。它是可直接调用的,当模块混合到另一个类中时,它不会出现在包含的类中。