Possible Duplicate:
Ruby method Array#<< not updating the array in hash
Strange ruby behavior when using Hash.new([])
I've been doing Koans which is great, and as I go along I find no major trouble, but I stumbled upon this, and can't make any sense out of it:
def test_default_value_is_the_same_object
hash = Hash.new([])
hash[:one] << "uno"
hash[:two] << "dos"
assert_equal ["uno", "dos"], hash[:one] # But I only put "uno" for this key!
assert_equal ["uno", "dos"], hash[:two] # But I only put "dos" for this key!
assert_equal ["uno", "dos"], hash[:three] # I didn't shove anything for :three!
assert_equal true, hash[:one].object_id == hash[:two].object_id
end
All the tests are passing (I just looked at the error which helped me guess the right assertions to write).
The last assert, ok, they both were not initialized so their values have got to have the same object ID since they both take the default.
I don't understand why the default value was altered, I'm not even entirely sure that's what happened.
I tried it out in IRB, thinking maybe some tampering on Hash/Array was done to make me crazy, but I get the same result.
I first thought hash[:one] << "uno"
would imply hash
to become { one: ["uno] }
, but it remains { }
.
Although I'm guessing <<
only calls push
, and new keys are only added when you use the =
sign
Please tell me what I missed.
EDIT: I'm using Ruby 1.9.3