Reputation: 2329
I don't understand how Ruby hashes work.
I expect these:
a = 'a'
{a => 1}[a] # => 1
{a: 1}[:a] # => 1
{2 => 1}[2] # => 1
How does this work?
{'a' => 1}['a'] # => 1
The first string 'a'
is not the same object as the second string 'a'
.
Upvotes: 0
Views: 58
Reputation: 80075
As a footnote to other answers, you can let a hash behave like you expected:
h = {'a'=> 1}
p h['a'] #=> 1
h.compare_by_identity
p h['a'] #=> nil ; not the same object
Upvotes: 3
Reputation: 84132
Ruby doesn't use object equality (equal?
) for comparing hash keys. It wouldn't be very useful if it did after all.
Instead it uses eql?
, which for strings is the same as ==
Upvotes: 3
Reputation: 230461
some_hash[k] = v
Basically, when you do this, what is stored is not a direct association k => v
. Instead of that, k
is asked for a hash code, which is then used to map to v
.
Equal values yield equal hash codes. That's why your last example works the way it does.
A couple of examples:
1.9.3p0 :001 > s = 'string'
=> "string"
1.9.3p0 :002 > 'string'.hash
=> -895223107629439507
1.9.3p0 :003 > 'string'.hash == s.hash
=> true
1.9.3p0 :004 > 2.hash
=> 2271355725836199018
1.9.3p0 :005 > nil.hash
=> 2199521878082658865
Upvotes: 1