基本上我正在尝试将具有相同值的这一个哈希数组压缩到另一个数组中。我是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'}
]
任何帮助?
答案 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"
}
]