How do I get the unique elements from an array of hashes in Ruby?

后端 未结 8 944
抹茶落季
抹茶落季 2020-12-28 14:57

I have an array of hashes, and I want the unique values out of it. Calling Array.uniq doesn\'t give me what I expect.

a = [{:a => 1},{:a =&g         


        
8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-28 15:19

    You can use (tested in ruby 1.9.3),

    [{a: 1},{a: 2},{a:1}].uniq => [{a:1},{a: 2}]
    [{a: 1,b: 2},{a: 2, b: 2},{a: 1, b: 3}].uniq_by {|v| v[:a]} => [{a: 1,b: 2},{a: 2, b: 2}]
    

提交回复
热议问题