何时在模块的方法中使用 self [英] When to use self in module's methods

查看:38
本文介绍了何时在模块的方法中使用 self的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模块定义如下所示:

My module definition looks like this:

module RG::Stats
  def self.sum(a, args = {})
    a.inject(0){ |accum, i| accum + i }
  end
end

要使用此方法,我只需要包含此定义的文件,以便我可以:

To use this method I simply require the file containing this definition so that I can do:

RG::Stats.sum(array)

还有

RG::Stats.method(:sum)

但是,如果我需要知道使用 RG::Stats.instance_methods 的方法列表,我会得到一个空数组.这是因为我使用了self.如果我省略 self 那么 RG::Stats.instance_methods 会给出方法列表,但我不能再访问它们了.

However, if I need to know the list of methods using RG::Stats.instance_methods I get an empty array. This is because I have used self. If I omit self then RG::Stats.instance_methods gives the list of methods, but I cannot access them anymore.

问题是:如何在模块的方法定义中使用self?

The question is: how to use self in module's method definition?

推荐答案

在每个方法定义中使用 self 如果您希望方法仅在模块的单例类中定义(其中方法使用 self live 定义).如果您希望模块的方法同时定义为实例方法和单例方法,则省略 self 和 extend self.

Use self in each method definition if you want the methods to be defined only in the singleton class of the module (where the methods defined using self live). Omit self and extend self if you want the methods of the module to be defined as instance methods and singleton methods at the same time.

例如,您可以使用 RG::Stats.sum(array) 调用该方法,并且如果您这样做,它仍然会由 instance_methods 方法列出:

For instance, you can call the method using RG::Stats.sum(array) and still have it listed by the instance_methods method if you do this:

module RG::Stats
  extend self

  def sum(a, args = {})
    a.inject(0){ |accum, i| accum + i }
  end
end

这样,sum方法就被定义为一个实例方法,使用extend self后,它被包含在模块的单例类中.

This way, the sum method is defined as an instance method and it is included in the singleton class of the module after using extend self.

您可以检查RG::Stats模块的实例方法来验证这一点:

You can check the instance methods of RG::Stats module to verify this:

RG::Stats.instance_methods
=> [:sum]

使用这种技术,您不必担心定义没有 self 关键字的方法,因为模块不能有实例,因此不能像 RG 的实例方法一样调用它::Stats 模块.由于 extend self 语句,它只能作为单例方法 RG::Stats.sum(array) 调用.

With this technique you don't have to worry about defining the method without the self keyword because modules can't have instances so it cannot be called like an instance method of RG::Stats module. It can only be called as a singleton method RG::Stats.sum(array) thanks to the extend self statement.

这篇关于何时在模块的方法中使用 self的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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