开发者

Ruby, assert_equal of two arrays of objects

开发者 https://www.devze.com 2023-02-16 06:30 出处:网络
I have the following situation. I am trying to write a unit test for an array of objects. The object is defined something 开发者_如何学Clike this:

I have the following situation. I am trying to write a unit test for an array of objects. The object is defined something 开发者_如何学Clike 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消