New Alexandria
New Alexandria

Reputation: 7324

How does Ruby allow an array to be a Hash key?

I recently learned that you can use an array as a Hash key

How does Ruby accomplish this?

Upvotes: 2

Views: 204

Answers (2)

steenslag
steenslag

Reputation: 80065

From the docs:

Two objects refer to the same hash key when their hash value is identical and the two objects are eql? to each other.

Okay, what does Array#eql? do?

Returns true if self and other are the same object, or are both arrays with the same content (according to Object#eql?)

Upvotes: 2

Dan Tao
Dan Tao

Reputation: 128317

It isn't the pointer or the object_id. Ruby allows you to sort of treat arrays as values, so two arrays containing the same elements produce the same hash value.

Here, look:

arr1 = [1, 2]
arr2 = [1, 2]

# You'll see false here
puts arr1.object_id == arr2.object_id

# You'll see true here
puts arr1.hash == arr2.hash

hash = {}
hash[arr1] = 'foo'
hash[arr2] = 'bar'

# This will output {[1, 2] => 'bar'},
# so there's only one entry in the hash
puts hash

The Hash class in Ruby uses the hash method of an object to determine its uniqueness as a key. So that's why arr1 and arr2 are interchangeable in the code above (as keys).

Upvotes: 5

Related Questions