Ruby如何允许数组成为哈希键?

时间:2023-01-24 21:43:34

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

我最近了解到可以使用数组作为哈希键

How does Ruby accomplish this?

Ruby是如何做到这一点的?

  • Is the Array pointer the hash key?
  • 数组指针是哈希键吗?
  • Or is it the array_instance's object_id?
  • 还是array_instance的object_id?
  • Or something else?
  • 还是别的?

2 个解决方案

#1


5  

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.

它不是指针或object_id。Ruby允许您将数组视为值,因此包含相同元素的两个数组产生相同的散列值。

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).

Ruby中的散列类使用对象的散列方法来确定其作为键的惟一性。这就是为什么arr1和arr2在上面的代码中可以互换(作为键)。

#2


2  

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.

当两个对象的哈希值相同且两个对象是eql时,两个对象引用相同的哈希键?的相互关系。

Okay, what does Array#eql? do?

好的,数组# eql什么?做什么?

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

如果self和other是相同的对象,或者两个数组都具有相同的内容(根据object #eql?)

#1


5  

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.

它不是指针或object_id。Ruby允许您将数组视为值,因此包含相同元素的两个数组产生相同的散列值。

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).

Ruby中的散列类使用对象的散列方法来确定其作为键的惟一性。这就是为什么arr1和arr2在上面的代码中可以互换(作为键)。

#2


2  

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.

当两个对象的哈希值相同且两个对象是eql时,两个对象引用相同的哈希键?的相互关系。

Okay, what does Array#eql? do?

好的,数组# eql什么?做什么?

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

如果self和other是相同的对象,或者两个数组都具有相同的内容(根据object #eql?)