Quoting Chris McMahon [email protected]:
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