On Sun, Jun 8, 2008 at 10:25 PM, nico Itkin [email protected]
wrote:
Thanks evebody for yours answers, helps a lot !
Jesús : looks fantastic, but could you give me fex explanation how it
works?
a = Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)}
is this a way to override the method new for the object a?
You’re doing so by passing the following block but then i’m lost, do you
have any links to share which detail that ?
Hash.new receives a block, which is executed whenever you try to access
a non-existing key. In the block you can assign a value to the key in
the hash.
The value that we assign above is a hash. If we did this:
a = Hash.new {|h,k| h[k] = Hash.new}
Then we would achieve a two-level hash, but the second level hash,
wouldn’t be able to assign a next level hash to a non-existing key,
because
a block wasn’t provided.
Hash has a default_proc variable that contains the block (in proc form)
that was passed to the constructor, so if we assign this proc as the
block
for the constructor, we get a hash that can assign a hash to a
non-existing key,
in a recursive way, cause each hash will pass its default proc to the
hash
created in the constructor block.
So many words that I don’t know if I made myself clear…