From: mental@... Date: 2005-12-01T07:29:00+09:00 Subject: Re: Help constructing interesting hash? Quoting Chris McMahon : > Suppose I have an array of arrays like > > [[A, B, C][1,2,3]] > > I can easily make a hash (using each_with_index) where one value > is > the lookup value for the other value: > > 1=>A > 2=>B > 3=>C def build( values, keys ) hash = {} values.zip( keys ) do |value, key| hash[key] = value end hash end build(*[[A, B, C], [1, 2, 3]]) #=> {1=>A, 2=>B, 3=>C} > Now suppose I have a AoA like > > [[A, B, C,][1,2,2]] > > Is there a readable way to construct a hash like > > 1=>[A] > 2=>[B, C] def build2( values, keys ) hash = {} values.zip( keys ) do |value, key| ( hash[key] ||= [] ).push value end hash end build2(*[[A, B, C], [1, 2, 2]]) #=> {1=>[A], 2=>[B, C]} In other words, you can probably just take the code you've got and replace: hash[key] = value with: ( hash[key] ||= [] ).push value This bit can also be written in longer form as: hash[key] ||= [] hash[key].push value or even: hash[key] = [] unless hash[key] hash[key].push value (but the shortest form saves you one or two hash lookups) -mental