Remove adjacent identical elements in a Ruby Array?

前端 未结 6 1571
醉酒成梦
醉酒成梦 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:49

    another solution:

    acc = [a[0]]
    a.each_cons(2) {|x,y| acc << y if x != y}
    

    or

    a.each_cons(2).inject([a[0]]) {|acc, (x,y)| x == y ? acc : acc << y}
    

提交回复
热议问题