是否有一种简单的方法可以迭代2个数组并找到两个数组中完全相同的元素值并将其填充到新数组中?
例如:
arr_a = ["a","b","c","d"]
arr_b = ["123","456","b","d","c"]
我想要创建的数组是:
new_arr = ["b","c","d"]
我试过了:
another_arr = [*arr_a, *arr_b] #combines the 2 arrays
another_arr.select { |e| another_arr.count(e) >1 }.uniq #then find all dupes
但我不知道如何将结果推送到数组。
这是正确的方式吗?有没有想法如何将结果推送到数组?
答案 0 :(得分:5)
您尝试做的是Set Intersection,可以使用&
运算符在Ruby中实现。
arr_a = ["a","b","c","d"]
arr_b = ["123","456","b","d","c"]
new_array = arr_a & arr_b
在" ary & other_ary"。
中详细了解相关信息答案 1 :(得分:1)
你正在寻找两组交集。这样更简单:
arr_a & arr_b