How to count duplicates in Ruby Arrays

后端 未结 16 1789
清歌不尽
清歌不尽 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 07:01

    I've used reduce/inject for this in the past, like the following

    array = [1,5,4,3,1,5,6,8,8,8,9]
    array.reduce (Hash.new(0)) {|counts, el| counts[el]+=1; counts}
    

    produces

    => {1=>2, 5=>2, 4=>1, 3=>1, 6=>1, 8=>3, 9=>1}
    

提交回复
热议问题