Remove adjacent identical elements in a Ruby Array?

前端 未结 6 1724
醉酒成梦
醉酒成梦 2021-02-14 12:55

Ruby 1.8.6

I have an array containing numerical values. I want to reduce it such that sequences of the same value are reduced to a single instance of that value.

6条回答
  •  太阳男子
    2021-02-14 13:25

    For the simplest, leanest solution, you could use the method Enumerable#chunk:

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

    The itself method is Ruby 2.2+. Use {|n| n} if you are stuck in an older Ruby, or my backports gems. It was introduced in Ruby 1.9.2. If you're unlucky enough to be using older rubies, you could use my backports gem and require 'backports/1.9.2/enumerable/chunk'.

提交回复
热议问题