Remove adjacent identical elements in a Ruby Array?

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'.


a.inject([]){|acc,i| acc.last == i ? acc : acc << i }

Tags:

Arrays

Ruby