Pergunta

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!

Foi útil?

Solução

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"]}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top