I was going through Ruby Koans tutorial series, when I came upon this in about_hashes.rb:
def test_default_value_is_the_same_object
hash = Hash.new([])
hash[:one] << "uno"
hash[:two] << "dos"
assert_equal ["uno", "dos"], hash[:one]
assert_equal ["uno", "dos"], hash[:two]
assert_equal ["uno", "dos"], hash[:three]
assert_equal true, hash[:one].object_id == hash[:two].object_id
end
The values in assert_equals, is actually what the tutorial expected. But I couldn’t understand how there is a difference between using << operator and = operator?
My expectation was that:
hash[:one]would be["uno"]hash[:two]would be["dos"]hash[:three]would be[]
Can someone please explain why my expectation was wrong?
When you’re doing
hash = Hash.new([])you are creating a Hash whose default value is the exact same Array instance for all keys. So whenever you are accessing a key that doesn’t exist, you get back the very same Array.If you want one array per key, you have to use the block syntax of
Hash.new:Edit: Also see what Gazler has to say with regard to the
#<<method and on what object you are actually calling it.