arr = [1,2,1,3,5,2,4]
如何通过排序按组值对数组进行计数?我需要以下输出:
x[1] = 2
x[2] = 2
x[3] = 1
x[4] = 1
x[5] = 1
最佳答案
x = arr.inject(Hash.new(0)) { |h, e| h[e] += 1 ; h }
关于ruby - 如何在不使用循环的情况下按数组中的计数分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5470725/