Join GitHub today
GitHub is home to over 31 million developers working together to host and review code, manage projects, and build software together.Sign up
BigDecimal#hash returns different value for numerically equal numbers #772
irb(main):003:0> BigDecimal.new("2").hash == BigDecimal.new("2.0").hash => false irb(main):004:0> BigDecimal.new("2") == BigDecimal.new("2.0") => true irb(main):005:0> BigDecimal.new("2").eql?(BigDecimal.new("2.0")) => true
1.9.3p125 :002 > BigDecimal.new('2').hash == BigDecimal.new('2.0').hash => true 1.9.3p125 :003 > BigDecimal.new('2') == BigDecimal.new('2.0') => true 1.9.3p125 :004 > BigDecimal.new('2').eql?(BigDecimal.new('2.0')) => true
MRI must be using a different mechanism than us for calculating the hash of BigDecimal. In JRuby, they are both using the JDK's implementation, i.e. java.math.BigDecimal#hashCode. One wonders why the JDK folks did not want equal values to hash the same...it is worth investigating before we go off implementing MRI's behavior. For what it's worth, these are two distinct BigDecimals, since "2" only has one significant figure and "2.0" has two.
According to the BigDecimal#hashCode javadocs:
And an easy solution to this would be to call BigDecimal#stripTrailingZeros before calling BigDecimal#hashCode. @headius, does that sound like the right thing to do? If so, I can put together the patch and specs.