Christopher K. Christopher K. - 11 months ago 63
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 - 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] = []