Remove adjacent identical elements in a Ruby Array?

Posted by Mike Woodhouse on Stack Overflow See other posts from Stack Overflow or by Mike Woodhouse
Published on 2010-03-25T14:29:11Z Indexed on 2010/03/25 14:33 UTC
Read the original article Hit count: 244

Filed under:
|

Ruby 1.8.6

I have an array containing numerical values. I want to reduce it such that sequences of the same value are reduced to a single instance of that value.

So I want

a = [1, 1, 1, 2, 2, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3]

to reduce to

[1, 2, 3, 2, 3]

As you can see, Array#uniq won't work in this case.

I have the following, which works:

(a.size - 1).downto(1) { |i| a[i] = nil if a[i - 1] == a[i] }

Can anyone come up with something less ugly?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about arrays