In the first case, the default value returned when the key does not exist is [] . Then various statements successfully add different dogs and squirrels to the returned arrays.
However, it is by no means the key ever created for :dogs or :squirrels.
In the second case, the block saves the new value back to the hash record using the key.
Interestingly, here is a little more interesting, as you continue to receive a new empty array in the first case. And the answer is this: you did not pass [] as a parameter, but as a block. This executable file is saved as proc. Each time a key is not found, proc starts again and generates a new [] .
You can see this in the operation, pay attention to the different values ββof the object identifier:
irb > t = Hash.new { [] } => {} irb > t[:a].object_id => 2149202180 irb > t[:a].object_id => 2149192500
source share