Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove adjacent identical elements in a Ruby Array?

Tags:

arrays

ruby

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?

like image 673
Mike Woodhouse Avatar asked Mar 25 '10 14:03

Mike Woodhouse


1 Answers

For the simplest, leanest solution, you could use the method Enumerable#chunk:

a.chunk(&:itself).map(&:first)

The itself method is Ruby 2.2+. Use {|n| n} if you are stuck in an older Ruby, or my backports gems. It was introduced in Ruby 1.9.2. If you're unlucky enough to be using older rubies, you could use my backports gem and require 'backports/1.9.2/enumerable/chunk'.

like image 74
Marc-André Lafortune Avatar answered Oct 16 '22 19:10

Marc-André Lafortune