Home  >  Q&A  >  body text

[算法]如何用ruby统计数组或哈希中不同元素的个数?

例如有如下数据:

a,b,c,a,c,d

※数据出现不固定,可能有e,f,g等。

查了ruby文档的array和hash,没想出怎么实现。

黄舟黄舟2713 days ago735

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-21 11:19:01

    Get the values ​​of different data:

    %w(a b c a c d).uniq
    

    Get the number of occurrences of each element:

    count_hash = {}
    %w(a b c a c d).each do |item|
      key = item.to_sym
      if count = count_hash[key]
        count_hash[key] = count + 1
      else
        count_hash[key] = 1
      end
    end
    

    reply
    0
  • 迷茫

    迷茫2017-04-21 11:19:01

    str='a,b,c,a,c,d'
    
    counter = Hash.new(0)
    
    str.split(',').each { |val| counter[val]+=1 }
    
    puts counter
    

    reply
    0
  • Cancelreply