How to count duplicates in Ruby Arrays

后端 未结 16 1616
清歌不尽
清歌不尽 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:41

    I don't think there's a built-in method. If all you need is the total count of duplicates, you could take a.length - a.uniq.length. If you're looking for the count of a single particular element, try
    a.select {|e| e == my_element}.length.

    0 讨论(0)
  • 2020-12-01 06:43
    arr = [1, 2, "a", "a", 4, "a", 2, 1]
    
    arr.group_by(&:itself).transform_values(&:size)
    #=> {1=>2, 2=>2, "a"=>3, 4=>1}
    
    0 讨论(0)
  • 2020-12-01 06:44

    Another version of a hash with a key for each element in your array and value for the count of each element

    a = [ 1, 2, 3, 3, 4, 3]
    h = Hash.new(0)
    a.each { | v | h.store(v, h[v]+1) }
    
    # h = { 3=>3, 2=>1, 1=>1, 4=>1 } 
    
    0 讨论(0)
  • 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"]
    
    0 讨论(0)
  • 2020-12-01 06:48

    What about a grep?

    arr = [1, 2, "Thanks", "You're welcome", "Thanks", "You're welcome", "Thanks", "You're welcome"]
    
    arr.grep('Thanks').size # => 3
    
    0 讨论(0)
  • 2020-12-01 06:48

    Another way to do it is to use each_with_object:

    a = [ 1, 2, 3, 3, 4, 3]
    
    hash = a.each_with_object({}) {|v, h|
      h[v] ||= 0
      h[v] += 1
    }
    
    # hash = { 3=>3, 2=>1, 1=>1, 4=>1 } 
    

    This way, calling a non-existing key such as hash[5] will return nil instead of 0 with Kim's solution.

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