How to count duplicates in Ruby Arrays

后端 未结 16 1795
清歌不尽
清歌不尽 2020-12-01 06:21

How do you count duplicates in a ruby array?

For example, if my array had three a\'s, how could I count that

16条回答
  •  无人及你
    2020-12-01 06:46

    requires 1.8.7+ for group_by

    ary = %w{a b c d a e f g a h i b}
    ary.group_by{|elem| elem}.select{|key,val| val.length > 1}.map{|key,val| key}
    # => ["a", "b"]
    

    with 1.9+ this can be slightly simplified because Hash#select will return a hash.

    ary.group_by{|elem| elem}.select{|key,val| val.length > 1}.keys
    # => ["a", "b"]
    

提交回复
热议问题