0

基本上我试图将这个具有相同值的哈希数组压缩到另一个数组中。我是 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'}
]

有什么帮助吗?

4

1 回答 1

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"
  }
]
于 2013-09-11T16:54:11.567 回答