Stephen C Stephen C - 11 days ago 7
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
end
end

keys = keys.uniq


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

Answer
input.reduce { |e, acc| acc.merge(e) { |_, e1, e2| [*e2, *e1] } }
#⇒ {:name=>["sam", "max", "joe"],
#   :animal=>["dog", "cat", "snake"],
#   :gender=>["male", "female", "male"]}
Comments