【问题标题】:ruby super keyword in initialize throws ArgumentError初始化中的 ruby​​ super 关键字引发 ArgumentError
【发布时间】:2015-06-03 09:20:22
【问题描述】:

我正在从一本基于 ruby​​ 1.9 的书中学习 ruby​​,但目前我使用的是 2.2

我有两门课(来自书中)

class Point
    def initialize(x,y)
        @x,@y = x,y
    end
end

class Point3D < Point
    def initialize(x,y,z)
        super(x,y)
        @z = z
    end
end

但是,当我调用 Point3D.new(0,1,2) 时,ruby 解释器会引发一个 ArgumentError,上面写着 wrong number of arguments (3 for 2)

为什么会这样?

编辑

我没有说 Point 类在另一个 required 文件中。

我试过打电话

require "./Point.rb"

point = Point.new(0,1)
puts point

按预期工作

然后按照上面的描述添加 Point3D 类并尝试调用

require "./Point.rb"

class Point3D < Point
...
end

point1 = Point3D.new(0,1,2)
puts point1

引发 ArgumentError。

如果我将两个类放在同一个文件 (Point3D.rb) 中,则不会发生此问题,但如果我将 Point3D 类放在 Point.rb 中,错误仍然存​​在。

【问题讨论】:

  • 2.1.2 和 2.2.0 似乎都可以正常工作。只能看到两种情况会出现该错误 - super 被不带参数调用并使用 3 个参数初始化 Point。
  • 从我的代码中很明显我没有这样做。
  • 2.1, 2.2 @linux:不可重现。
  • 适用于 1.9.3
  • 好吧,用require_relative "Point"代替require "./Point.rb"

标签: ruby oop


【解决方案1】:

我明白问题出在哪里了。

本书以如何创建initialize重载为例

class Point
    def initialize(x,y)
        @x,@y = x,y
    end

    def self.new(x,y)
        #other stuff
        super
    end
end

它缺少来自Point3Dsuper 呼叫

我已评论 self.newPoint 正在按预期工作。

有趣的是,如果你像这样在Point.rb文件中为Point添加方法

class << Point
    def to_s
        "foo"
    end
end

Point.rb 工作正常。

【讨论】:

  • 一个好的做法是尝试运行您在此处发布的确切代码,看看它是否可以在没有任何其他代码的情况下工作。否则我们对您的问题一无所知。
猜你喜欢
  • 2016-09-14
  • 2017-05-26
  • 2018-06-23
  • 2010-10-23
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
  • 2017-10-29
  • 1970-01-01
相关资源
最近更新 更多