Ruby模块方法

时间:2018-06-21 17:13:28

标签: ruby

我正在浏览有关Ruby模块的在线教程,扩展了老师在其中解释代码的地方

module Tracking
  def create(name)
    object = new(name)
    instances.push(object) # note this line
    return object
  end

  def instances
    @instances ||= []
  end
end



class Customer
  extend Tracking

  attr_accessor :name
  def initialize(name)
    @name = name
  end

  def to_s
    "[#{@name}]"
  end
end

这是输出

puts "Customer.instances: %s" % Customer.instances.inspect
puts "Customer.create: %s" % Customer.create("Jason")
puts "Customer.create: %s" % Customer.create("Kenneth")
puts "Customer.instances: %s" % Customer.instances.inspect

Output:

Customer.instances: [] 

Customer.create: [Jason]

Customer.create: [Kenneth]

Customer.instances: [#<Customer:0x007f2b23eabc08 @name="Jason">, #<Customer:0x007f2b23eabaf0 @name="Kenneth">]

我对extends的工作方式有所了解,但我不明白的是这种方法

def create(name)
        object = new(name)
        instances.push(object)
        return object
end

特别是instances.push(object)线

应该不是@instances.push(object)

instances是模块中的方法,我们如何push将对象作为方法,它不是数组,而是包含数组。

这是怎么回事?

拜托,我是Ruby的新手,我将非常感谢简单的答案。

1 个答案:

答案 0 :(得分:1)

instances返回@instances,这是一个数组,这就是为什么当您push将其放入其中时,将其推入@instances(变量)而不是{ {1}}(方法)。

调用instances将创建带有空白数组的instances并返回空白数组,从而为您提供一个占位符以将内容保留在其中。

据您所知,您甚至可以执行以下操作:

@instances
相关问题