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

2 comments:

Unknown said...

Alternative:

map = Hash.new{|hash, key| hash[:key] = []}

Unknown said...

There's a typo in my previous post. 'key' shouldn't be a symbol. It should be:

hash[key] = []