将模块方法调用到 Ruby 中的另一个模块中 [英] calling module method into another module in Ruby

查看:43
本文介绍了将模块方法调用到 Ruby 中的另一个模块中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件模块.rb

module CardExpiry
  def check_expiry value
    return true
  end
end

文件包含.rb

#raise File.dirname(__FILE__).inspect
require "#{File.dirname(__FILE__)}/module.rb"

 module Include
     include CardExpiry
  def self.function 
    raise (check_expiry 1203).inspect
  end
end

打电话

Include::function

这可能吗?

调用时触发错误:

`function': undefined method `check_expiry' for Include:Module (NoMethodError)

推荐答案

您偶然发现了 includeextend 的区别.

You stumbled over the difference of include and extend.

  • include 使包含的模块中的方法可用于您的类的实例
  • extend 使包含模块中的方法在 class
  • 中可用
  • include makes the method in the included module available to instances of your class
  • extend makes the methods in the included module available in the class

当用self.method_name 定义一个方法并在该方法中访问self 时,self 绑定到当前类.

When defining a method with self.method_name and you access self within that method, self is bound to the current class.

check_expiry 已包含在内,因此仅在实例端可用.

check_expiry, however, is included and thus only available on the instance side.

要解决此问题,请扩展 CardExpiry,或将 check_expiry 设为类方法.

To fix the problem either extend CardExpiry, or make check_expiry a class method.

这篇关于将模块方法调用到 Ruby 中的另一个模块中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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