Reputation: 133
Basically I'm trying to condense this one array of hashes with the same value into another array. I'm new to Ruby and I'm trying to change this
fruit = [
{type: 'grape', color: 'purple' },
{type: 'grape', shape: 'round'},
{type: 'grape', size: 'small'},
{type: 'apple', color: 'red'},
{type: 'apple', size: 'med'},
]
to this:
fruit = [
{type: 'grape', color: 'purple', shape: 'round', size: 'small'}
{type: 'apple', color: 'red', size: 'med'}
]
Any help?
Upvotes: 0
Views: 116
Reputation: 168199
fruit.group_by{|h| h[:type]}.values.map{|a| a.inject(:merge)}
Result:
[
{
:type => "grape",
:color => "purple",
:shape => "round",
:size => "small"
},
{
:type => "apple",
:color => "red",
:size => "med"
}
]
Upvotes: 2