Ruby,两个对象数组的assert_equal

发布于 2024-10-21 01:56:07 字数 467 浏览 4 评论 0原文

我有以下情况。我正在尝试为对象数组编写单元测试。该对象的定义如下:

class Element
  attr_reader :title, :season, :episode

  def initialize ( name, number )
    @name = name
    @number = number
  end

  def to_s
    number = "%02d" % @number

    result = "Number " << number << " " << @name
    result
  end
end

在测试期间,我断言两个数组,它们都包含三个元素,元素相同,甚至顺序相同,但我仍然收到断言不相等的错误。我想我在这里遗漏了一些非常基本的东西,有什么问题吗?

如果我通过 to_s 方法比较每个元素,则断言是正确的..这是应该首先完成的方式吗?

I have the following situation. I am trying to write a unit test for an array of objects. The object is defined something like this:

class Element
  attr_reader :title, :season, :episode

  def initialize ( name, number )
    @name = name
    @number = number
  end

  def to_s
    number = "%02d" % @number

    result = "Number " << number << " " << @name
    result
  end
end

During the test I assert two arrays which both contain three elements, the elements are identical and even the order is identical still I get an error that the assert isn't equal. I guess I am missing something really basic here, whats the catch?

If I compare each element by the to_s method, the assert is correct.. Is that the way it should be done in the first place?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦途 2024-10-28 01:56:07

尝试使用以下代码为您的类声明一个方法 ==

def ==(other)
  self.to_s == other.to_s
end

旁注,您可能也想重构您的 to_s 方法,以获得一些简洁的代码。

def to_s
  "Number %02d #{@name}" % @number
end

编辑:

Numbers 已经定义了 == 方法(https://github.com/evanphx/rubinius/blob/master/kernel/bootstrap/fixnum.rb#L117)。

Ruby 通过对数组的每个元素运行 == 比较来比较数组。下面是数组上 == 的实现,如 Rubinius 中所做的那样(几乎完全用 Ruby 本身编写的 Ruby 实现)https://github.com/evanphx/rubinius/blob/master/kernel/common/array.rb#L474

如果忽略各种错误检测,它基本上会递归地对数组的所有元素运行 == ,如果所有元素都匹配,则返回 true。

Try declaring a method == for your class, with the following code.

def ==(other)
  self.to_s == other.to_s
end

Sidenote, you might want to refactor your to_s method too, for some concise code.

def to_s
  "Number %02d #{@name}" % @number
end

Edit:

Numbers already have an == method defined (https://github.com/evanphx/rubinius/blob/master/kernel/bootstrap/fixnum.rb#L117).

Ruby compares arrays by running an == compare on each element of an Array. Here's the implementation of == on Arrays, as done in Rubinius (a Ruby implementation written almost completely in Ruby itself) https://github.com/evanphx/rubinius/blob/master/kernel/common/array.rb#L474.

If you leave out various error detections, it basically runs an == on all the elements of the array, recursively, and returns true if all of them match.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文