Saturday, March 1, 2008

Ruby initialise array and add in one step

I keep forgetting the syntax of this so perhaps this will help.

Given a hash where each value is an array of values this gives a nice concise way of setting things up (even if it is a little obscure).

map = {}

(map[:key] ||= []) << :value

The above results in a hash containing a key value of :key with an array containing :value