如何迭代哈希数组并在Ruby中计算重复结果

时间:2014-02-14 21:33:34

标签: ruby arrays hash

我有一个名为cleanconnections的哈希数组

[{:name=>"John Doe1", :number=>"5551234567"},
{:name=>"John Doe1", :number=>"5551234567"},
{:name=>"John Doe2", :number=>"5557654321"},
{:name=>"John Doe1", :number=>"5551234567"}]

我希望能够在cleanconnections中将类似的数组组合在一起,最后得到数组内的计数,例如:

[{:name=>"John Doe1", :number=>"5551234567", :count=>3},
{:name=>"John Doe2", :number=>"5557654321", :count=>1}]

我试过了:

count = { }
cleanconnections.map { |name,number| 
    namenumber = name.zip(number)
    count[{namenumber => count += 1}]
}

但结果是:

TypeError: wrong argument type NilClass (must respond to :each)
        from (irb):2367:in `zip'
        from (irb):2367:in `block in irb_binding'
        from (irb):2365:in `map'
        from (irb):2365
        from /usr/bin/irb:12:in `<main>'

以及尝试:

cleanconnections.each {|x| 
    x.store(x, count[x] +1 )
}

但结果是:

NoMethodError: undefined method `+' for nil:NilClass
        from (irb):2376:in `block in irb_binding'
        from (irb):2375:in `each'
        from (irb):2375
        from /usr/bin/irb:12:in `<main>'

我已经尝试将这两个放在

unless x.nil? 

但这并未改变错误。

你可能会说,我对红宝石很新。谁能帮助我指出正确的方向?我很感激!此外,首先发布stackoverflow,所以反馈也很感激。感谢

1 个答案:

答案 0 :(得分:4)

此问题之前已得到解答,但总有改进的余地:

a = [{:name=>"John Doe1", :number=>"5551234567"},
     {:name=>"John Doe1", :number=>"5551234567"},
     {:name=>"John Doe2", :number=>"5557654321"},
     {:name=>"John Doe1", :number=>"5551234567"}]

a.group_by{|h|h}.map{|k,v|k[:count]=v.size;k}
# => [{:name=>"John Doe1", :number=>"5551234567", :count=>3},
#     {:name=>"John Doe2", :number=>"5557654321", :count=>1}]