perezdr perezdr - 7 months ago 81
Ruby Question

Ruby Array of Arrays Group and Count by Values

I'm trying to get a Ruby Array of Arrays and group it in order to count its values.

The Array has a month, and a boolean:

array = [["June", false], ["June", false], ["June", false], ["October", false]]

I will like to end with a new Array that let me know how many false vs trues in each month.

Example: (where the first item in the Array is month, the second is the count of false and the third is the count of true)

new_array = [["June", 3, 0]], ["October", 1, 0]]


Using Enumerable#group_by:

Array.group_by { |month, b| month }.map{ |month, xs|
   xs.count {|_, b| !b},  # false
   xs.count {|_, b| b}]   # true
# => [["June", 3, 0], ["October", 1, 0]]