I think you are putting the cart before the horse. You are asking yourself: "How can I get uniq
to remove objects which aren't equal?" But what you should be asking yourself, is: "Why aren't those two objects equal, despite the fact that I consider them to be?"
In other words: it seems you are trying to work around the fact that your objects have broken equality semantics, when what you really should do is simply fixing those broken equality semantics.
Here's an example for a Product
, where two products are considered equal if they have the same type number:
class Product
def initialize(type_number)
self.type_number = type_number
end
def ==(other)
type_number == other.type_number
end
def eql?(other)
other.is_a?(self.class) && type_number.eql?(other.type_number)
end
def hash
type_number.hash
end
protected
attr_reader :type_number
private
attr_writer :type_number
end
require 'test/unit'
class TestHashEquality < Test::Unit::TestCase
def test_that_products_with_equal_type_numbers_are_considered_equal
assert_equal 2, [Product.new(1), Product.new(2), Product.new(1)].uniq.size
end
end