Last Updated: February 25, 2016
·
618
· robcole

Removing consecutive duplicate lines using Enumerable

Ran into a situation today where I needed to remove duplicate lines of text from an array, but ONLY if they were consecutive. Fortunately, ruby >= 1.9.2 makes this fairly easy.

arr = arr.chunk {|x| x }.map(&:first)

Thanks to http://stackoverflow.com/questions/4576652/how-do-you-merge-consecutive-repeating-elements-in-an-array for the tip.