binarymason binarymason - 2 months ago 11
Ruby Question

How to "reduce" array of hashes with duplicate keys to nested hash?


Note: There were a few similar questions on SO about this, like here
and here, but none seem quite like what I'm looking for.


Say I have an array of hashes like this:

arr_with_dup_hsh_keys = [
{ foo: "dup", bar: 1 },
{ foo: "dup", bar: 2 },
{ foo: "dup", bar: 3 },
{ foo: "dup", bar: 4 },
{ foo: "dup", bar: 5 }
]


How do I reduce that down to this?

{ foo: "dup", bars: [1, 2, 3, 4, 5] }

Answer

If your data is really as simple as in your question, this will do what you want:

{ foo: "dup",
  bars: arr_with_dup_hsh_keys.map {|hsh| hsh[:bar] }
}