Count sequential occurrences of element in ruby array

Here's one line solution. The logic same as Matt suggested, though, works fine with nil's in front of x:

x.each_with_object([]) { |e, r| r[-1] && r[-1][0] == e ? r[-1][-1] +=1 : r << [e, 1] }

This is not a general solution, but if you only need to match single characters, it can be done like this:

x.join.scan(/(\w)(\1*)/).map{|x| [x[0], x.join.length]}

1.9 has Enumerable#chunk for just this purpose:

x.chunk{|y| y}.map{|y, ys| [y, ys.length]}

Tags:

Ruby