问题
I want to group a collection of objects by their has many relations... like this
s.inventoryitems.group_by{|i| i.locations}
For the sake of simplicity this returns me something like this:
{[1, 2, 3]=>["a"], [2]=>["b", "c"], []=>["d"]}
I'm looking for a result like this though:
{[1] => ["a"], [2] => ["a","b","c"], [3] => ["a"], [] => ["d"]}
I am working on restructuring things so this can all be done in a more intuitive DB & model association oriented way, but in the meantime I need implement this immediately and need to wrangle it with some Ruby and am not sure. Thanks for any help!
回答1:
You need to expand this, invert it, and re-group it if you want to flip the structure like that. You could do this simply by iterating over it and regrouping manually:
h = { [ 1, 2, 3 ] => [ "a" ], [ 2 ] => [ "b", "c" ], [ ] => [ "d" ] }
s = { }
h.each do |keys, values|
keys.each do |key|
values.each do |value|
s[[ key ]] ||= [ ]
s[[ key ]] << value
end
end
if (keys.empty?)
s[[ ]] = values
end
end
puts s.inspect
# => {[1]=>["a"], [2]=>["a", "b", "c"], [3]=>["a"], []=>["d"]}
来源:https://stackoverflow.com/questions/4684441/rails-enumerable-group-by-multiple-associations