如果我不想从数组中删除重复元素,而是想删除具有特定共同属性的元素,该怎么办?
具体来说,我想从数组中删除具有重复“essences”的所有字符串,其中essence 的定义如下:
class String
def essence
downcase.gsub('&', 'and').gsub(/[^a-z0-9]/, '')
end
end
我想要这样的东西:
['a', 'A', 'b'].uniq_by(&:essence)
# => ['a', 'b'] (or ['A', 'b']; I don't really care)
实现这一目标的最佳方法是什么?
从1.9.2开始,Array#uniq http://ruby-doc.org/core-1.9.2/Array.html#method-i-uniq (and uniq! http://ruby-doc.org/core-1.9.2/Array.html#method-i-uniq-21)占用一个块,所以不再需要uniq_by
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)