Project

General

Profile

Actions

Bug #16850

closed

Object#hash doesn't behave as documented

Added by ana06 (Ana Maria Martinez Gomez) over 1 year ago. Updated over 1 year ago.

Status:
Closed
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:98290]

Description

From Ruby 2.7 Object class documentation:

The hash value is used along with eql? by the Hash class to determine if two objects reference the same hash key.

From this I expect that overwritting the Object#hash method changes the Hashing algorithm. But this is only the case for some objets. Consider the following code:

class Object
  def hash
    i_dont_exist
  end 
end

class Ana 
end

hash = {}
hash[3] = true
hash[3] = false
puts 'Integers are not using the new hash method'
hash[Ana.new] = true
puts 'this will not be executed because the class Ana uses the new hash method'

The output of executing this code is:

Integers are not using the new hash method
Traceback (most recent call last):
        1: from a.rb:13:in `<main>'
a.rb:3:in `hash': undefined local variable or method `i_dont_exist' for #<Ana:0x000055626f0b7a30> (NameError)

This proves that Integer hash method is not used to determine if two objects reference the same hash key, as said in the documentation. Check the any_hash method for the other classes affected.

I think that either the behavior should be modified (aiming for a consistency along different classes and following the documentation) or the documentation updated.

Actions

Also available in: Atom PDF