如何查找与两个数组匹配的所有数组元素

adb*_*ads 0 ruby arrays

有没有一种简单的方法来迭代2个数组并找到两个数组中完全相同的任何元素值并将其填充到新数组中?

例如:

arr_a = ["a","b","c","d"]

arr_b = ["123","456","b","d","c"]
Run Code Online (Sandbox Code Playgroud)

我想要创建的数组是:

new_arr = ["b","c","d"]
Run Code Online (Sandbox Code Playgroud)

我试过这个:

another_arr = [*arr_a, *arr_b] #combines the 2 arrays
another_arr.select { |e| another_arr.count(e) >1 }.uniq #then find all dupes
Run Code Online (Sandbox Code Playgroud)

但我不知道如何将结果推送到数组.

这是正确的方式吗?有没有想法如何将结果推送到数组?

小智 5

您尝试做的是Set Intersection,可以使用&运算符在Ruby中实现.

arr_a = ["a","b","c","d"]

arr_b = ["123","456","b","d","c"]

new_array = arr_a & arr_b
Run Code Online (Sandbox Code Playgroud)

在" ary&other_ary "中阅读更多相关信息.