Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count sequential occurrences of element in ruby array

Tags:

ruby

Given some array such as the following:

x = ['a', 'b', 'b', 'c', 'a', 'a', 'a']

I want to end up with something that shows how many times each element repeats sequentially. So maybe I end up with the following:

[['a', 1], ['b', 2], ['c', 1], ['a', 3]]

The structure of the results isn't that important... could be some other data types of needed.

like image 229
Larsenal Avatar asked Nov 17 '11 07:11

Larsenal


1 Answers

1.9 has Enumerable#chunk for just this purpose:

x.chunk{|y| y}.map{|y, ys| [y, ys.length]}
like image 75
pguardiario Avatar answered Oct 07 '22 22:10

pguardiario