How to count duplicates in Ruby Arrays

后端 未结 16 1618
清歌不尽
清歌不尽 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}
    
    0 讨论(0)
  • 2020-12-01 07:03

    Improving @Kim's answer:

    arr = [1, 2, "a", "a", 4, "a", 2, 1]
    Hash.new(0).tap { |h| arr.each { |v| h[v] += 1 } }
    # => {1=>2, 2=>2, "a"=>3, 4=>1}
    
    0 讨论(0)
  • 2020-12-01 07:06

    To count instances of a single element use inject

    array.inject(0){|count,elem| elem == value ? count+1 : count}
    
    0 讨论(0)
  • 2020-12-01 07:07

    Its Easy:

    words = ["aa","bb","cc","bb","bb","cc"]
    

    One line simple solution is:

    words.each_with_object(Hash.new(0)) { |word,counts| counts[word] += 1 }
    

    It works for me.

    Thanks!!

    0 讨论(0)
提交回复
热议问题