“base.send:include,InstanceMethods”--->这是做什么的?

时间:2009-06-10 04:11:27

标签: ruby

我正在查看一个模块X,它包含两个名为“InstanceMethods”和“ClassMethods”的模块。

模块X中的最后一个定义是:

  def self.included(base)
    base.send :include, InstanceMethods
    base.send :extend,  ClassMethods
  end

这是做什么的?

3 个答案:

答案 0 :(得分:9)

只要模块包含在另一个模块或类中,就会调用

included。在这种情况下,它将尝试调用base的{​​{1}}方法来将include中的模块方法,变量和常量添加到InstanceMethods中,然后尝试调用{ {1}} base方法将base中的实例方法添加到extend

也可能是

ClassMethods

答案 1 :(得分:1)

'send'调用其第一个参数作为其调用的对象的方法,其余参数作为参数发送给方法。所以在这种情况下,

base.send :include, InstanceMethods

相当于

base.include(InstanceMethods)

将InstanceMethods模块中的方法添加到“基础”对象

答案 2 :(得分:0)

它定义了一个带有参数“base”的类方法。然后,它会调用include上的extendbase方法,分别将模块InstanceMethodsClassMethods作为参数传递。对include的调用会将InstanceMethods中定义的实例方法添加到base。我不熟悉extend方法,但我认为它也会做类似的事情,但对于类方法。