Reputation: 328
I have the following:
h1 = {}
h1.compare_by_identity
h1['a'] = '1'
h1['a'] = '2'
h1['a'] = '3'
a_key = h1.keys.first
p h1[a_key]
And it prints 1, how do I make it return 2 or 3?
Upvotes: 1
Views: 349
Reputation: 3424
that's because 'a'
it's a different object each time.
'a'.object_id == 'a'.object_id
=> false
a = 'a'
a.object_id == a.object_id
=> true
You can try using the same object/instance, or a Symbol.
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
Upvotes: 0
Reputation: 20796
how do I make it return 2 or 3?
h1[h1.keys[0]] # => "1"
h1[h1.keys[1]] # => "2"
h1[h1.keys[2]] # => "3"
You can of course access the list of values directly, but I don't think this is in the spirit of your question:
h1.values # => ["1", "2", "3"]
Upvotes: 1