查找两个数组之间的共同值

时间:2012-04-19 14:24:52

标签: ruby

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

这就是我的尝试但却没有得到结果。

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]

3 个答案:

答案 0 :(得分:114)

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

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

答案 1 :(得分:16)

x = [1, 2, 4]
y = [5, 2, 4]
intersection = (x & y)
num = intersection.length
puts "There are #{num} numbers common in both arrays. Numbers are #{intersection}"

将输出:

There are 2 numbers common in both arrays. Numbers are [2, 4]

答案 2 :(得分:2)

好的,所以&运算符似乎是获得此答案所需要做的唯一事情。

但在我知道我为数组类编写了一个快速的猴子补丁之前,这样做了:

class Array
  def self.shared(a1, a2)
    utf = a1 - a2 #utf stands for 'unique to first', i.e. unique to a1 set (not in a2)
    a1 - utf
  end
end

虽然&运算符是正确答案。更优雅。