Why is this hash:
test_hash = Hash.new{|hash, key|
Hash.new{|second_level_hash, second_level_key| 0 }
}
not updated by the following operation?
test_hash[1][1] += 1
test_hash[1][1] # => 0
Why is this hash:
test_hash = Hash.new{|hash, key|
Hash.new{|second_level_hash, second_level_key| 0 }
}
not updated by the following operation?
test_hash[1][1] += 1
test_hash[1][1] # => 0
You're not actually assigning the value to the Hash, you're just returning a Hash and an independent 0 value. These get modified, then thrown away.
Fix this by performing an assignment:
test_hash = Hash.new { |h,k|
h[k] = Hash.new(0)
}
You can tell something was wrong because after accessing test_hash[1][1]
then calling test_hash.inspect
it's still empty.
tadman's answer is (halfway) correct, but may be a bit misleading.
You are assigning a value to the embedded hash, but not assigning the embedded hash to the main hash. Each time a key is called in the main hash, a new embedded hash is created. After you have assigned a value to the embedded hash, the embedded hash that has become {1 => 1}
is not assigned to the main hash, and is thrown away.