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

后端 未结 8 1073
抹茶落季
抹茶落季 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:30

    I can get what I want by calling inject

    a = [{:a => 1},{:a => 2}, {:a => 1}]
    a.inject([]) { |result,h| result << h unless result.include?(h); result }
    

    This will return:

    [{:a=>1}, {:a=>2}]
    

提交回复
热议问题