删除在Ruby数组相邻的相同的元素? [英] Remove adjacent identical elements in a Ruby Array?
本文介绍了删除在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.
所以,我想
a = [1, 1, 1, 2, 2, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3]
,以减少
[1, 2, 3, 2, 3]
正如你所看到的,阵列#uniq的
不会在这种情况下工作。
As you can see, Array#uniq
won't work in this case.
我有以下,其工作方式:
I have the following, which works:
(a.size - 1).downto(1) { |i| a[i] = nil if a[i - 1] == a[i] }
任何人都可以拿出更少的丑陋的东西吗?
Can anyone come up with something less ugly?
推荐答案
对于最简单的,最瘦的解决方案,你可以使用的方法<一个href=\"http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-chunk\"><$c$c>Enumerable#chunk$c$c>:
For the simplest, leanest solution, you could use the method Enumerable#chunk
:
a.chunk{|n| n}.map(&:first)
这是用Ruby 1.9.2引入的。如果你够倒霉使用旧的红宝石是,你可以用我的 backports中
一>宝石和要求'反向移植/ 1.9.2 /枚举/块'
。
这篇关于删除在Ruby数组相邻的相同的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文