I want to group objects that are virtually the same but not identical like in this case:
class MyClass
attr_accessor :value
def initialize(value)
@value = value
end
def ==(other)
(@value - other.value).abs < 0.0001
end
end
With the precision relevant for my implementation, two values differing by 0.0001 can be regarded identical:
MyClass.new(1.0) == MyClass.new(1.00001)
# => true
I want these to be in the same group:
[MyClass.new(1.0), MyClass.new(1.00001)].group_by(&:value)
# => {1.0=>[#<MyClass:0x0000000d1183e0 @value=1.0>], 1.00001=>[#<MyClass:0x0000000d118390 @value=1.00001>]}
What comparison is used for group_by
? Can the built in group_by
be made to honor the custom ==
method, or is a custom group_by
method required for this?