Why does the test_default_value_is_the_same_object in about_hashes.rb of Ruby Koans exercises have the answer of an array?

Viewed 749

I'm doing the ruby koans exercises and am a bit confused about why the answers are such in the test_default_value_is_the_same_object method exercises. Below is the code:

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]
end

I'm not sure why no matter what the key is, the value is always "uno" and "dos"? I thought when the key is one, the returned value should be "uno"; when key is "two", the returned value should be "dos". Why no matter what the keys are, the value is always an array?

Thank you and I'm looking forward to your answer!

2 Answers

I had the same question and found this answer which didn't really explain why this is confusing to those just learning it. After looking closer I found why it behaves the way it does.

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

Look at the assignment lines:

  hash[:one] << "uno"
  hash[:two] << "dos"

Each assignment is a reference to a non-existent key, which points to the default key, then using the append operator (<<) adds an element to the default key's array. Thus all calls to the default key's array are now ["uno", "dos"].

That is also why the assert comparing the id's of both calls (hash[:one] and hash[:two]) as equal is true; they both reference the default key.

Related