开发者

Eliminate consecutive duplicates of list elements

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


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.


Do this (provided that each element is a single character)

list.join.squeeze.split('')


Ruby 1.9+

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

with respect to @sawa, who told me about with_index :)

As @Marc-André Lafortune noticed if there is nil at the end of your list it won't work for you. We can fix it with this ugly structure

list.select.with_index{|e,i| i < (list.size-1) and e != list[i+1]}


# 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[ a a a a b c c a a d e e e e ])
p list
#=> ["a", "b", "c", "a", "d", "e"]


arr = ['a','a','a','a','b','c','c','a','a','d','e','e','e','e']

enum = arr.each
  #=> #<Enumerator: ["a", "a", "a", "a", "b", "c", "c", "a", "a", "d",
  #                  "e", "e", "e", "e"]:each>
a = []
loop do
  n = enum.next
  a << n unless n == enum.peek
end
a #=> ["a", "b", "c", "a", "d"]

Enumerator#peek raises a StopIteration exception when it has already returned the last element of the enumerator. Kernel#loop handles that exception by breaking out of the loop.

See Array#each and Enumerator#next. Kernel#to_enum1 can be used in place of Array#each.

1 to_enum is an Object instance method that is defined in the Kernel module but documented in the Object class. Got that?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜