> -----Original Message-----
> From: robb.shecter / gmail.com [mailto:robb.shecter / gmail.com]
> Sent: Tuesday, May 27, 2008 12:09 PM
> To: ruby-talk ML
> Subject: Can someone explain this syntax in new?
>
> I found this in an old post:
>
>
> "Here's a Hash that automatically creates new hashes for each key you
> try to access (specifically 1-level deep for a '2-dimensional' hash):
>
>   people = Hash.new{ |me,key| me[ key ] = {} }
>   people[ :gavin ][ :age ] = 34
>   people[ :gavin ][ :sex ] = :male
>   people[ :fido ][ :species ] = :dog
>   p people
>   #=> {:gavin=>{:age=>34, :sex=>:male}, :fido=>{:species=>:dog}}
>
>
>
> ...but there was no further explanation.  Could somebody explain the
> syntax in the first line?  Is this overwriting new()?

No, this is calling new() with a block. In this case, for keys that are not yet in the hash, the specified block will be called with 2 parameters: one is the hash object itself, and the second one a key being accessed. This gives you an opportunity to initialize a value at that key appropriately (in the example before, it is initialized to another hash - {} is a literal for a hash, equivalent to Hash.new).

Gennady.

>
> Thanks,
> Robb
> --
> Posted via http://www.ruby-forum.com/.