我正在尝试获取一个 Ruby 数组数组并将其分组以计算其值。
数组有一个月份和一个 bool 值:
array = [["June", false], ["June", false], ["June", false], ["October", false]]
我想以一个新数组作为结尾,让我知道每个月有多少假与真。
示例:(数组中的第一项是月份,第二项是 false 的计数,第三项是 true 的计数)
new_array = [["June", 3, 0]], ["October", 1, 0]]
最佳答案
使用 Enumerable#group_by
:
Array.group_by { |month, b| month }.map{ |month, xs|
[month,
xs.count {|_, b| !b}, # false
xs.count {|_, b| b}] # true
}
# => [["June", 3, 0], ["October", 1, 0]]
关于arrays - Ruby Array of Arrays 按值分组和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38067083/