TIL: Counting Consecutive Items in a Ruby Array
I wanted to know how many times a thing occurs consecutively in array. Only consecutive items are important
I wanted to know how many times a thing occurs consecutively in array. Only consecutive items are important.
So using Ruby's Enumerable#chunk
method...
[1, 1, 2, 2, 3, 1, 1]
.chunk { |x| x }
.map { |x, xs| [x, xs.count] }
# => [[1, 2], [2, 2], [3, 1], [1, 2]]
Member discussion