Ruby:模块,要求并包含 [英] Ruby: module, require and include

查看:69
本文介绍了Ruby:模块,要求并包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use Ruby modules (mixins).

我有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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆