2014-02-25 27 views
0
animals = [ 
    {type: "dog", a: 2}, 
    {type: "dog", b: 7}, 
    {type: "dog", c: 2}, 
    {type: "cat", d: 3}, 
    {type: "cat", e: 4}, 
    {type: "cat", f: 0}, 
    {type: "rabbit", g: 0}, 
    {type: "rabbit", h: 1} 
] 

如何转换成如何获取数组中的这些独特元素并一起折叠?

animals = [ 
    {type:"dog", a:2, b:7, c:2}, 
    {type:"cat", d:3, e:4, f:0}, 
    {type:"rabbit", g:0, h:1} 
] 

我不知道如何做到这一点的一个好办法。 使用each和使用ifelse语句来提取太笨拙。 任何想法?

+2

你不能在一个散列中重复键,你可以实现的最好的就像'动物= [{狗:1,年龄:[2,7,2]},''。 – toro2k

+0

有趣的是,他所期望的结果结构在irb中评估为=> [{:dog => 1,:age => 2},{:cat => 3,:age => 0},{:rabbit => 5,:年龄=> 1}] – mvw

+0

@ toro2k对不起,错误..我现在把这些关键字独一无二 –

回答

6

我下面做:

animals = [ 
    {type: "dog", a: 2}, 
    {type: "dog", b: 7}, 
    {type: "dog", c: 2}, 
    {type: "cat", d: 3}, 
    {type: "cat", e: 4}, 
    {type: "cat", f: 0}, 
    {type: "rabbit", g: 0}, 
    {type: "rabbit", h: 1} 
] 

array_of_merged_hash = animals.group_by do |inner_hash| 
    inner_hash[:type] 
end.map { |_,v| v.reduce(:merge) } 

array_of_merged_hash 
# => [{:type=>"dog", :a=>2, :b=>7, :c=>2}, 
#  {:type=>"cat", :d=>3, :e=>4, :f=>0}, 
#  {:type=>"rabbit", :g=>0, :h=>1}] 

方法是:group_byreducemap

+1

优秀和优雅的解决方案! –

+0

@Rafa非常感谢你! :-) –

+0

非常感谢。如果我不是一个红宝石经验丰富的人,很难想到这样的方法。 –

相关问题