ruby 如果元素不存在,则将其添加到数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14004325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add element to an array if it's not there already
提问by Alan Coromano
I have a Ruby class
我有一个 Ruby 课程
class MyClass
attr_writer :item1, :item2
end
my_array = get_array_of_my_class() #my_array is an array of MyClass
unique_array_of_item1 = []
I want to push MyClass#item1to unique_array_of_item1, but only if unique_array_of_item1doesn't contain that item1yet. There is a simple solution I know: just iterate through my_arrayand check if unique_array_of_item1already contains the current item1or not.
我想推MyClass#item1送到unique_array_of_item1,但前提是unique_array_of_item1还没有包含它item1。我知道有一个简单的解决方案:只需迭代my_array并检查是否unique_array_of_item1已经包含当前item1。
Is there any more efficient solution?
有没有更有效的解决方案?
回答by Jason Denney
@Coorassehas a good answer, though it should be:
my_array | [item]
And to update my_arrayin place:
并my_array就地更新:
my_array |= [item]
回答by doesterr
You don't need to iterate through my_arrayby hand.
您不需要my_array手动迭代。
my_array.push(item1) unless my_array.include?(item1)
Edit:
编辑:
As Tombart points out in his comment, using Array#include?is not very efficient. I'd say the performance impact is negligible for small Arrays, but you might want to go with Setfor bigger ones.
正如 Tombart 在他的评论中指出的那样,使用Array#include?效率不是很高。我会说对小型阵列的性能影响可以忽略不计,但您可能想要使用Set更大的阵列。
回答by coorasse
You can convert item1 to array and join them:
您可以将 item1 转换为数组并加入它们:
my_array | [item1]
回答by elreimundo
Important to keep in mind that the Set class and the | method (also called "Set Union") will yield an array of uniqueelements, which is great if you want no duplicates but which will be an unpleasant surprise if you have non-unique elements in your original array by design.
重要的是要记住 Set 类和 | 方法(也称为“设置联合”)将产生一个唯一元素数组,如果您不希望重复,这很好,但如果您的原始数组中设计有非唯一元素,这将是一个令人不快的惊喜。
If you have at least one duplicate element in your original array that you don't want to lose, iterating through the array with an early return is worst-case O(n), which isn't too bad in the grand scheme of things.
如果您的原始数组中至少有一个您不想丢失的重复元素,那么在最坏情况下迭代数组并提前返回是 O(n),这在总体上还算不错.
class Array
def add_if_unique element
return self if include? element
push element
end
end
回答by witkacy26
I'm not sure if it's perfect solution, but worked for me:
我不确定这是否是完美的解决方案,但对我有用:
host_group = Array.new if not host_group.kind_of?(Array)
host_group.push(host)

