查找两个数组之间的共同值 [英] Find values in common between two arrays

查看:39
本文介绍了查找两个数组之间的共同值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想比较两个数组并创建一个内插输出字符串,如果数组 y 中的数组变量存在于 x 中,我如何获得每个匹配元素的输出?

If I want to compare two arrays and create an interpolated output string if an array variable from array y exists in x how can I get an output for each matching element?

这就是我正在尝试但没有完全得到结果的方法.

This is what I was trying but not quite getting the result.

x = [1, 2, 4]
y = [5, 2, 4]
x.each do |num|
  puts " The number #{num} is in the array" if x.include?(y.each)
end #=> [1, 2, 4]

推荐答案

可以使用集合交集方法 &:

You can use the set intersection method & for that:

x = [1, 2, 4]
y = [5, 2, 4]
x & y # => [2, 4]

这篇关于查找两个数组之间的共同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆