Ruby, assert_equal of two arrays of objects

I have the following situation. I am trying to write unit test for an array of objects. An object is defined 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 claim two arrays that contain three elements, the elements are identical, and even the order is identical, but I get an error that the statement is not equal. I guess I am missing something really elementary here, what is the catch?

If I compare each element using the to_s method, the statement is correct. So should this be done first?

+3
source share
1 answer

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 reorganize your to_s method for some short code.

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

Edit:

== (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, .

+3

All Articles