Ruby:模块、需要和包含 [英] Ruby: module, require and include
本文介绍了Ruby:模块、需要和包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 Ruby 模块(mixins).
I'm trying to use Ruby modules (mixins).
我有 test.rb:
I have test.rb:
#!/usr/bin/env ruby
require_relative 'lib/mymodule'
class MyApp
include MyModule
self.hallo
end
和 lib/mymodule.rb:
and lib/mymodule.rb:
module MyModule
def hallo
puts "hallo"
end
end
非常简单的设置.但它不起作用:(:
Quite simple setup. But it does not work :( :
ruby test.rb
test.rb:8:in `<class:MyApp>': undefined method `hallo' for MyApp:Class (NoMethodError)
from test.rb:6:in `<main>'
我的错误在哪里?
推荐答案
简而言之:你需要extend
而不是include
模块.
In short: you need to extend
instead of include
the module.
class MyApp
extend MyModule
self.hallo
end
include
为混合它的类提供实例方法.
include
provides instance methods for the class that mixes it in.
extend
为混合它的类提供类方法.
extend
provides class methods for the class that mixes it in.
阅读这个.
这篇关于Ruby:模块、需要和包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文