I'm working through the Ruby Koans in order to get a better grasp on Ruby and TDD. I got to Line 93 in the code in about_hashes.rb
and this confuses me how it would be shoveled into the default constructor instead of the hash value. Just out of curiosity I tried using the same thing with a string as the parameter of the constructor and it produced a similar result.
Now my question is why, whatever key I use, the same object is retrieved and how would I shovel a new object into the array at a specific key in a hash in the method test_default_value_is_the_same_object
?
def test_default_value_is_the_same_object
hash = Hash.new([])
hash[:one] << "uno"
hash[:two] << "dos"
assert_equal ["uno", "dos"], hash[:one] #why not ["uno"]?
assert_equal ["uno", "dos"], hash[:two] #why not ["dos"]?
assert_equal ["uno", "dos"], hash[:three] #why not []?
assert_equal true, hash[:one].object_id == hash[:two].object_id
end
def test_default_value_with_block
hash = Hash.new {|hash, key| hash[key] = [] }
hash[:one] << "uno"
hash[:two] << "dos"
assert_equal ["uno"], hash[:one]
assert_equal ["dos"], hash[:two]
assert_equal [], hash[:three]
end