Ruby: Testing objects for equality

Ruby has three main equality test methods:

== 

eql?

equal?

These all do the same thing. However, you may want to override a method to test your own objects for equality. In this case the Ruby way tends to be to leave equal? alone and override the eql? and == methods.

E.g. 

class Sock

  attr_reader :size

  def initialize size

    @size = size

  end

 

  def ==(another_sock) # overriding the == method

    self.size == another_sock.size

  end

end

sock1 = Sock.new(10)

sock2 = Sock.new(11)

sock3 = Sock.new(10)

 

puts “Are sock1 and sock2 equal? #{sock1 == sock2}”

puts “Are sock1 and sock3 equal? #{sock1 == sock3}”

which gives:

Are sock1 and sock2 equal? false

Are sock1 and sock3 equal? true

More here:

http://www.skorks.com/2009/09/ruby-equality-and-object-comparison/

Leave a Reply

Your email address will not be published. Required fields are marked *