最快/单行的方式收集在Ruby中数组复制? [英] Fastest/One-liner way to collect duplicates in Ruby Array?
本文介绍了最快/单行的方式收集在Ruby中数组复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是最快/单行的方式转换成一个这样的数组:
What's the fastest/one-liner way to convert an array like this:
[1,1,1,1,2,2,3,5,5,5,8,13,21,21,21]
...成对象的一个这样的数组:
...into an array of objects like this:
[{1 => 4},{2 => 2},{3 => 1},{5 => 3},{8 => 1},{13 => 1 },{21 => 3}]
推荐答案
要达到你想要的格式,你可以追加调用映射到您的解决方案:
To achieve your desired format, you could append a call to map to your solution:
array.inject({}) { |h,v| h[v] ||= 0; h[v] += 1; h }.map {|k, v| {k => v}}
虽然它仍然是一个班轮,它开始变得混乱。
Although it still is a one-liner, it starts to get messy.
这篇关于最快/单行的方式收集在Ruby中数组复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文