在Ruby中的同一数组中压缩哈希数组

时间:2013-09-11 16:40:45

标签: ruby-on-rails ruby arrays

基本上我正在尝试将具有相同值的这一个哈希数组压缩到另一个数组中。我是Ruby的新手,我正试图改变这个

fruit = [
 {type: 'grape', color: 'purple' },
 {type: 'grape', shape: 'round'},
 {type: 'grape', size: 'small'},
 {type: 'apple', color: 'red'},
 {type: 'apple', size: 'med'},

]

到此:

fruit = [
  {type: 'grape', color: 'purple', shape: 'round', size: 'small'}
  {type: 'apple', color: 'red', size: 'med'}
]

任何帮助?

1 个答案:

答案 0 :(得分:2)

fruit.group_by{|h| h[:type]}.values.map{|a| a.inject(:merge)}

结果:

[
  {
    :type  => "grape",
    :color => "purple",
    :shape => "round",
    :size  => "small"
  },
  {
    :type  => "apple",
    :color => "red",
    :size  => "med"
  }
]