Stephen C Stephen C - 1 year ago 85
Ruby Question

Group Array of Hashes by Key followed by values

Assuming I have the following dataset

:name => "sam",
:animal => "dog",
:gender => "male"
}, {
:name => "max",
:animal => "cat",
:gender => "female"
}, {
:name => "joe",
:animal => "snake",
:gender => "male"

How would you group the array of hashes to:

:name => ["sam", "max", "joe"]
:animal => ["dog", "cat", "snake"]
:gender => ["male", "female", "male"]

I've read similar articles such as this and Group array of hashes by key

However, most examples return the values as increment counts where I'm looking for actual separate values.

My attempt

keys = []
values = []

arr.each do |a|
a.each do |k, v|
keys << k
#this is where it goes wrong and where I'm stuck at
values << v

keys = keys.uniq

I understand where I went wrong is how I'm trying to segment the values. Any direction would be appreciated!

Answer Source
input.reduce { |e, acc| acc.merge(e) { |_, e1, e2| [*e2, *e1] } }
#⇒ {:name=>["sam", "max", "joe"],
#   :animal=>["dog", "cat", "snake"],
#   :gender=>["male", "female", "male"]}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download