Christopher K. Christopher K. - 2 years ago 93
Ruby Question

Understanding hash creation

I am very new to Ruby and I'm trying to understand the following hash creation:

hash = { |hash, key| hash[key] = [] }

How can I interpret it? The syntax (the content of the block) is not clear to me yet.

Answer Source - You're calling the Hash's constructor

{ |hash, key| hash[key] = [] } - you're passing this block to the constructor. This block says to the Hash: when you encounter an unknown key, create a new key/value pair, with that key as the key, and a newly allocated empty array as the value.

hash = - You're assigning the new hash to this variable. But don't use hash as a variable name! It's already the name of a method on every object whose class subclasses Object.

There is also a simpler notation:[])

but that is rarely what you want, because that will assign the same array to all values.

Regarding the syntax of |hash, key|, that fragment serves exactly the same purpose as the parenthesized argument list of a method, e.g. (hash, key) in the code below:

def f(hash, key)
  hash[key] = []
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download