例如有如下数据:
a,b,c,a,c,d
※数据出现不固定,可能有e,f,g等。
查了ruby文档的array和hash,没想出怎么实现。
人生最曼妙的风景,竟是内心的淡定与从容!
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
str='a,b,c,a,c,d' counter = Hash.new(0) str.split(',').each { |val| counter[val]+=1 } puts counter
Get the values of different data:
Get the number of occurrences of each element: