Exclude consecutive duplicates of list items

What is the best solution to eliminate consecutive duplicate list items?

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 it:

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

Ruby 1.9.2

+5
source share
4 answers

Good opportunity to use Enumerable#chunk introduced in Ruby 1.9.2 (if your list does not contain nil ):

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

In earlier Ruby, you can require "backports/1.9.2/enumerable/chunk" to get a clean version of Ruby.

+20
source

Do this (assuming each item is a single character)

 list.join.squeeze.split('') 
+4
source

Ruby 1.9+

 list.select.with_index{|e,i| e != list[i+1]} 

regarding @sawa who told me about with_index :)

As @ Marc-AndrΓ© Lafortune noted, if there is nil at the end of your list, this will not work. We can fix it with this ugly structure

 list.select.with_index{|e,i| i < (list.size-1) and e != list[i+1]} 
+3
source
 # Requires Ruby 1.8.7+ due to Object#tap def compress(items) last = nil [].tap do |result| items.each{ |o| result << o unless last==o; last=o } end end list = compress(%w[ aaaabccaadeeee ]) p list #=> ["a", "b", "c", "a", "d", "e"] 
+1
source

All Articles