Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eliminate consecutive duplicates of list elements

Tags:

ruby

What is the best solution to eliminate consecutive duplicates of list elements?

list = compress(['a','a','a','a','b','c','c','a','a','d','e','e','e','e']).
p list # => # ['a','b','c','a','d','e']

I have this one:

def compress(list)
  list.map.with_index do |element, index| 
    element unless element.equal? list[index+1]
  end.compact
end

Ruby 1.9.2

like image 648
Vasiliy Ermolovich Avatar asked Apr 04 '11 21:04

Vasiliy Ermolovich


1 Answers

Nice opportunity to use Enumerable#chunk, as long as your list doesn't contain nil:

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

For Ruby older than 2.2.x, you can require "backports/2.2.0/kernel/itself" or use {|x| x} instead of (&:itself).

For Ruby older than 1.9.2, you can require "backports/1.9.2/enumerable/chunk" to get a pure Ruby version of it.

like image 75
Marc-André Lafortune Avatar answered Oct 20 '22 17:10

Marc-André Lafortune