红宝石:计数数组中的独特元素及其OCCURENCES [英] Ruby: Count unique elements and their occurences in an array
本文介绍了红宝石:计数数组中的独特元素及其OCCURENCES的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有在Ruby中的方法接受一个数组,并计算所有独特的元素和它们的出现,并将他们带回作为哈希?
例如
['A','A','A','A','B','B','C'。方法
> {'A'=> 4,B=> 2,'C'=> 1}
类似的东西。
解决方案
['A','A','A','A','B','B' ,'C'] GROUP_BY {|。E | Ë} {.MAP | K,V | [K,v.length]}。to_h
Is there a method in Ruby that takes an array, and counts all unique elements and their occurrences and passes them back as a hash?
For example
['A','A','A','A','B','B','C'].method
> {'A' => 4, 'B' => 2, 'C' => 1}
Something like that.
解决方案
['A','A','A','A','B','B','C'].group_by{|e| e}.map{|k, v| [k, v.length]}.to_h
这篇关于红宝石:计数数组中的独特元素及其OCCURENCES的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文