ruby hash keys compare_by_identity

时间:2014-01-09 02:08:19

标签: ruby hash

我有以下内容:

h1 = {}
h1.compare_by_identity
h1['a'] = '1'
h1['a'] = '2'
h1['a'] = '3'
a_key = h1.keys.first
p h1[a_key]

它打印1,如何让它返回2或3?

2 个答案:

答案 0 :(得分:1)

  

如何让它返回2或3?

h1[h1.keys[0]] # => "1"
h1[h1.keys[1]] # => "2"
h1[h1.keys[2]] # => "3"

您当然可以直接访问值列表,但我认为这不符合您的问题:

h1.values # => ["1", "2", "3"]

答案 1 :(得分:0)

那是因为'a'每次都是不同的对象。

'a'.object_id == 'a'.object_id
=> false
a = 'a'
a.object_id == a.object_id
=> true

您可以尝试使用相同的对象/实例或符号。

h1 = {}
h1.compare_by_identity

h1['a'] = 1
puts h1['a'] # => nil

a = 'a'
h1[a] = 2
puts h1[a] # => 2

h1[:a] = 3
puts h1[:a] # => 3