这种符号是如何工作的? `object = Object.new [foo]`

时间:2014-05-10 17:43:13

标签: ruby

我看到了代码path = Path.new [edge] here

Ruby文档中的Object.new方法无法帮助我理解。

语法object = Object.new [foo]如何工作?

1 个答案:

答案 0 :(得分:3)

实际上是一个如下呼叫:

 Array.new [12] # => [12]

您的Path类是Array的子类。因此,它从您提到的行Path.new [edge]调用Array::new(array)

从GitHub lines我拿了如下代码: -

  # Adds distance method to compute the distance of the current path
  class Path < Array
    def distance
      (any?)? inject(0) { | sum, edge | sum += edge[LENGTH] } : INFINITY
    end
  end

这是一个以其他方式显示它的示例。我重写了Array::new方法: -

class Array
  def self.new
    12
  end
end

class Path < Array
  # code
end

Path.new # => 12