可能重复:
Remove from the array elements that are repeated. in Ruby如何删除有重复对象数组
我想做到这一点:
my_array = [1, 1, 2, 2, 3]
my_array_without_duplicates = [3]
调用my_array.uniq
会给我[1, 2, 3]
,这不是我想要的结果。有没有这样做的有效方式?我现在正在做的事太难看了。
可能重复:
Remove from the array elements that are repeated. in Ruby如何删除有重复对象数组
我想做到这一点:
my_array = [1, 1, 2, 2, 3]
my_array_without_duplicates = [3]
调用my_array.uniq
会给我[1, 2, 3]
,这不是我想要的结果。有没有这样做的有效方式?我现在正在做的事太难看了。
my_array.group_by{|e| e}.select{|k,v| v.count == 1}.keys
或
my_array.select{|e| my_array.count(e) == 1}
顺便说一句,你可能是指my_array = [1, 1, 2, 2, 3]
(用方括号,括号没有)。
我得到第一个输入的直方图(见Enumerable#frequency或写你自己的),然后做选择:
require 'facets'
xs = [1, 1, 2, 2, 3]
fs = xs.frequency # {1=>2, 2=>2, 3=>1}
ys = xs.select { |x| fs[x] == 1 } # [3]
Ruby 1.9的保持在哈希顺序,因此这可能就足够了:
xs.frequency.select { |x, count| count == 1 }.keys # [3]
它写在一个步骤,如果你使用Enumerable#map_select
抽象(假设你没有nil
S IN输入),像这样:
xs.frequency.map_select { |x, count| x if count == 1 } # [3]
我相信这在简单和效率之间具有良好的平衡。只是因为变量名很长而看起来很长。
my_array_without_duplicate = my_array.dup
my_array_without_duplicate.each_with_index {|e, i|
my_array_without_duplicate.delete(e) if my_array_without_dupliate.index(e, i+1)}
这不是有效的红宝石语法 - 你是指'[]',而不是'{}'? – Peter 2011-04-03 19:14:25
是的我已经更改为[]。速度打字FTL。 – David 2011-04-03 19:15:24
+1问题虽然 – Peter 2011-04-03 19:15:46