I did touch on this. If I can remember, I'll edit this comment later and put in the lecture number and slide number.
Anyway . . .
h = Hash.new { Array.new }
What is happening here is that the default is being set by a BLOCK, and the execution of the block is deferred until initialization time (of the new Hash element).
Here's the doc. Notice that I'm leaving out the |hash, key| params on the block, because the default value we want doesn't depend on them.
Returns a new, empty hash. If this hash is subsequently accessed by a key that doesn't correspond to a hash entry, the value returned depends on the style of +new+ used to create the hash. In the first form, the access returns +nil+. If _obj_ is specified, this single object will be used for all _default values_. If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block's responsibility to store the value in the hash if required.
I don't know if this was ever addressed, but how do you make it so that:
h = Hash.new(Array.new)
that the values of the has are *different* array objects??
I did touch on this. If I can remember, I'll edit this comment later and put in the lecture number and slide number.
Anyway . . .
h = Hash.new { Array.new }
What is happening here is that the default is being set by a BLOCK, and the execution of the block is deferred until initialization time (of the new Hash element).
Here's the doc. Notice that I'm leaving out the |hash, key| params on the block, because the default value we want doesn't depend on them.
Here's the doc:
Hash.new => hash
Hash.new(obj) => aHash
Hash.new {|hash, key| block } => aHash
From Ruby 1.9.1
Returns a new, empty hash. If this hash is subsequently accessed by a key that doesn't correspond to a hash entry, the value returned depends on the style of +new+ used to create the hash. In the first form, the access returns +nil+. If _obj_ is specified, this single object will be used for all _default values_. If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block's responsibility to store the value in the hash if required.
Thanks John!