user1717344
user1717344

Reputation: 133

Condensing an array of hashes within that same array in Ruby

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

Answers (1)

sawa
sawa

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

Related Questions