IRB中的Ruby Include模块

ore*_*nyk 2 ruby irb learn-ruby-the-hard-way

我正在研究Zed Shaw的" 学习Ruby The Hard Way",我遇到了一个问题,包括IRB中的一个模块.在练习25中,我们定义了一个新模块Ex25,在IRB中需要它,然后可以通过该模块的命名空间使用其各种方法,例如Ex25.break_words(sentence).在Extra Credit中,声明键入include Ex25将基本上将模块中的方法添加到当前"空间"(不确定要调用它),然后您可以在不明确引用模块的情况下调用它们,例如break_words(sentence).但是,当我这样做时,我得到一个"未定义的方法"错误.任何帮助/解释将不胜感激,谢谢!

jon*_*ahb 6

这是书中的错误.方法Ex25方法.include实例方法添加到"当前空间".self从方法定义中删除它将起作用:

module Ex25
  def break_words(stuff)
    stuff.split(' ')
  end
end

include Ex25
break_words 'hi there'  # => ["hi", "there"]
Run Code Online (Sandbox Code Playgroud)

如果你很好奇,这里有一些关于发生了什么的更多细节:包含方法的地方 - "当前空间" - 是Object类:

Object.included_modules  # => [Ex25, Kernel]
Run Code Online (Sandbox Code Playgroud)

所有Object实例都获得包含的方法......

Object.new.break_words 'how are you?'  # => ["how", "are", "you?"]
Run Code Online (Sandbox Code Playgroud)

...而顶级只是一个Object实例:

self.class  # => Object
Run Code Online (Sandbox Code Playgroud)

可是等等.如果顶级是一个Object实例,为什么它会响应include?(不是(和它的子类)include的实例方法?答案是顶级有一个单例方法......ModuleClass

singleton_methods.include? "include"  # => true
Run Code Online (Sandbox Code Playgroud)

...我们可以假设转发到Object类.