Ruby: module, require and include



我正在尝试使用Ruby模块(mixins)。

我有test.rb:

#!/usr/bin/env ruby
require_relative 'lib/mymodule'
class MyApp
  include MyModule
  self.hallo
end

和lib/mymodule.rb:

module MyModule
  def hallo
    puts "hallo"
  end
end

非常简单的设置。但是它不工作:(:

ruby test.rb
test.rb:8:in `<class:MyApp>': undefined method `hallo' for MyApp:Class (NoMethodError)
        from test.rb:6:in `<main>'

我的错误在哪里?

简而言之:您需要extend而不是include的模块。

class MyApp
  extend MyModule
  self.hallo
end

include为混合它的类提供了实例方法。

extend为混合它的类提供了类方法。

看一下

问题是您在类定义中调用hallo,而将其添加为实例方法(include)。

所以你可以使用extend (hallo将成为一个类方法):

module MyModule
  def hallo
    puts "hallo"
  end
end
class MyApp
  extend MyModule
  self.hallo
end

或者在MyApp的实例中调用hallo:

module MyModule
  def hallo
    puts "hallo"
  end
end
class MyApp
  include MyModule
end
an_instance = MyApp.new
an_instance.hallo

你的代码正在工作-但是包含一个模块并没有做你认为它做的事情。包含该模块的类将不会获得方法-该类中的对象将获得方法。

那么这个就可以了:

class MyApp
  include MyModule
end
my_app_object = MyApp.new
my_app_object.hallo # => hallo

my_a PP_object是MyApp类的对象,它有一个MyModule模块的mixins。

查看模块和mixins的完整解释。

相同
class MyApp
  extend MyModule
  self.hallo
end

extends只是打开类对象并包含模块方法。" hello "变成了一个类对象。MyApp类的静态方法

所以"include"将方法注入到接收者的实例中,在你的例子中是"self"而不是对象本身。"extend"向接收者注入方法,在你的例子中是"self"。

self.include MyModule // inject the methods into the instances of self
self.extend MyModule // inject the methods into object self

在类级别"self"将指向你的类对象MyApp。

还要记住,"include"one_answers"extend"只是在module.rb中定义的方法。"include"是一个类对象方法(静态方法),"extend"是一个实例方法。

最新更新