Search code examples
rubyblock

Can someone explain to me in detail what is going on in this Ruby block?


Learning Ruby. Needed to create a hash of arrays. This works... but I don't quite understand what Ruby is doing. Could someone explain it in detail?

months = Hash.new{|h, k| h[k] = []}

Solution

  • This uses the Hash.new constructor to create a hash whose items default to the empty list. You can therefore do something like this:

    months[2012] << 'January'
    

    and the array will be created without you doing a months[2012] = [] first.

    Short explanation: { |h, k| h[k] = [] } Is a Ruby block and as mu has mentioned, it can to some degree be compared to function in Javascript or lambda in Python. It basically is an anonymous piece of code that takes two arguments (h, k, the pipes only have the meaning to separate parameters from code) and returns a value. In this case it takes a hash and a key and sets the value of the key to a new array []. It returns a reference to the hash (but that's not important in this context).

    Now to Hash.new: It is the constructor for a Hash, of which I assume you already now what it is. It optionally takes a block as an argument that is called whenever a key is accessed that does not yet exist in the Hash. In the above example, the key 2012 was not accessed before, so the block is called, which creates a new array and assigns it to the key. Afterwards, the << operator can work with that array instance.