D
DK
Hello. I am new to Ruby. I am more familiar with Python, whose hash
keys are immutable, so I was surprised that Ruby's were not. When I
try to retrieve a value from a hash after manipulating the associated
key, it returns nil, even though it admits that the key in the hash
and the key I'm passing into the hash's [] method are the same:
irb(main):001:0> a=[1,2,3]
=> [1, 2, 3]
irb(main):002:0> b={a=>'test'}
=> {[1, 2, 3]=>"test"}
irb(main):003:0> b[a]
=> "test"
irb(main):004:0> a[0]=7
=> 7
irb(main):005:0> b[a]
=> nil
irb(main):006:0> b.keys[0] == a
=> true
irb(main):007:0> b
=> {[7, 2, 3]=>"test"}
# This is doubly weird:
irb(main):008:0> b[b.keys[0]]
=> nil
I'm sure someone has run into this before, but I was unable to find
anything on it. I am using ruby 1.8.5.
Thanks,
DK
keys are immutable, so I was surprised that Ruby's were not. When I
try to retrieve a value from a hash after manipulating the associated
key, it returns nil, even though it admits that the key in the hash
and the key I'm passing into the hash's [] method are the same:
irb(main):001:0> a=[1,2,3]
=> [1, 2, 3]
irb(main):002:0> b={a=>'test'}
=> {[1, 2, 3]=>"test"}
irb(main):003:0> b[a]
=> "test"
irb(main):004:0> a[0]=7
=> 7
irb(main):005:0> b[a]
=> nil
irb(main):006:0> b.keys[0] == a
=> true
irb(main):007:0> b
=> {[7, 2, 3]=>"test"}
# This is doubly weird:
irb(main):008:0> b[b.keys[0]]
=> nil
I'm sure someone has run into this before, but I was unable to find
anything on it. I am using ruby 1.8.5.
Thanks,
DK