user3163916
user3163916

Reputation: 328

ruby hash keys compare_by_identity

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

Answers (2)

wacko
wacko

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

Matt
Matt

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

Related Questions