消除连续重复列表元素的最佳解决方案是什么?
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版本.
红宝石 1.9+
\n\nlist.select.with_index{|e,i| e != list[i+1]}\nRun Code Online (Sandbox Code Playgroud)\n\n关于@sawa,他告诉我的with_index:)
正如@Marc-Andr\xc3\xa9 Lafortune 注意到的,如果你的列表末尾有 ,nil它对你不起作用。我们可以用这个丑陋的结构来修复它
list.select.with_index{|e,i| i < (list.size-1) and e != list[i+1]}\nRun Code Online (Sandbox Code Playgroud)\n