Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Ruby's Array.| compare elements for equality?

Tags:

ruby

Here's some example code:

class Obj
  attr :c, true

  def == that
    p '=='
    that.c == self.c
  end
  def <=> that
    p '<=>'
    that.c <=> self.c
  end
  def equal? that
    p 'equal?'
    that.c.equal? self.c
  end
  def eql? that
    p 'eql?'
    that.c.eql? self.c
  end
end

a = Obj.new
b = Obj.new

a.c = 1
b.c = 1

p [a] | [b]

It prints 2 objects but it should print 1 object. None of the comparison methods get called. How is Array.| comparing for equality?

like image 609
mxcl Avatar asked Mar 27 '10 15:03

mxcl


1 Answers

Array#| is implemented using hashs. So in order for your type to work well with it (as well as with hashmaps and hashsets), you'll have to implement eql? (which you did) and hash (which you did not). The most straight forward way to define hash meaningfully would be to just return c.hash.

like image 178
sepp2k Avatar answered Nov 15 '22 09:11

sepp2k