Ruby - 合并两个数组并删除重复的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33862557/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:18:30  来源:igfitidea点击:

Ruby - Merge two arrays and remove values that have duplicate

ruby-on-railsarraysruby

提问by user3204760

I have two arrays

我有两个数组

a = [1, 2, 3, 4, 5]

b = [2, 4, 6]

I would like to merge the two arrays, then remove the values that is the same with other array. The result should be:

我想合并两个数组,然后删除与其他数组相同的值。结果应该是:

c = [1, 3, 5, 6]

I've tried subtracting the two array and the result is [1, 3, 5]. I also want to get the values from second array which has not duplicate from the first array..

我试过将两个数组相减,结果是 [1, 3, 5]。我还想从第二个数组中获取与第一个数组不重复的值。

采纳答案by Rubyrider

You can do the following!

你可以做到以下几点!

# Merging
c = a + b
 => [1, 2, 3, 4, 5, 2, 4, 6]
# Removing the value of other array
# (a & b) is getting the common element from these two arrays
c - (a & b)
=> [1, 3, 5, 6]

Dmitri's comment is also same though I came up with my idea independently.

Dmitri 的评论也是一样的,虽然我是独立提出我的想法的。

回答by EJAg

Use Array#uniq.

使用Array#uniq.

a = [1, 3, 5, 6]
b = [2, 3, 4, 5]

c = (a + b).uniq
=> [1, 3, 5, 6, 2, 4]

回答by ironsand

How about this.

这个怎么样。

(a | b)
=> [1, 2, 3, 4, 5, 6]
(a & b)
=> [2, 4]

(a | b) - (a & b)
[1, 3, 5, 6]

Documentation for |method
Documentation for &method

文档|的方法
对文档&的方法

回答by noraj

Same as Array#uniq:

相同于Array#uniq

a = [1, 3, 5, 6]
b = [2, 3, 4, 5]

a|b
=> [1, 3, 5, 6, 2, 4]

Source

来源

回答by V K Singh

Let's have two array

让我们有两个数组

p = [1, 2, 5, 4, 8, 9]
q = [5, 6, 4, 8, 5, 3]

(p+q).uniq or (p.concat(q)).uniq

=> [1, 2, 5, 4, 8, 9, 6, 3]

Also p|qcan do the job! Decide which one suits for you.

p|q能胜任!决定哪一种适合你。

回答by Sig

How about Set.new([1,2,3]+[1,4,5])? Which returns [1,2,3,4,5]

怎么样Set.new([1,2,3]+[1,4,5])?哪个返回[1,2,3,4,5]