消除列表元素的连续重复

Vas*_*ich 6 ruby

消除连续重复列表元素的最佳解决方案是什么?

list = compress(['a','a','a','a','b','c','c','a','a','d','e','e','e','e']).
p list # => # ['a','b','c','a','d','e']
Run Code Online (Sandbox Code Playgroud)

我有这个:

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

Ruby 1.9.2

Mar*_*une 24

很好的机会Enumerable#chunk,只要您的列表不包含nil:

list.chunk(&:itself).map(&:first)
Run Code Online (Sandbox Code Playgroud)

对于早于2.2.x的Ruby,您可以require "backports/2.2.0/kernel/itself"使用或{|x| x}替代使用(&:itself).

对于早于1.9.2的Ruby,您require "backports/1.9.2/enumerable/chunk"可以获得它的纯Ruby版本.

  • 有一天,我会离开我懒惰的屁股并写一个REP为"Identity = - > x {x}"以包含在核心库中. (2认同)
  • @Jörg:或`Object#self`?然后可以写"&:self".在这两种情况下,我们都没有获得太多打字,但...... (2认同)

saw*_*awa 6

这样做(假设每个元素都是单个字符)

list.join.squeeze.split('')
Run Code Online (Sandbox Code Playgroud)


fl0*_*00r 5

红宝石 1.9+

\n\n
list.select.with_index{|e,i| e != list[i+1]}\n
Run Code Online (Sandbox Code Playgroud)\n\n

关于@sawa,他告诉我的with_index:)

\n\n

正如@Marc-Andr\xc3\xa9 Lafortune 注意到的,如果你的列表末尾有 ,nil它对你不起作用。我们可以用这个丑陋的结构来修复它

\n\n
list.select.with_index{|e,i| i < (list.size-1) and e != list[i+1]}\n
Run Code Online (Sandbox Code Playgroud)\n