2012-04-19 45 views
37

如果我想比较两个数组并创建一个插值输出字符串,如果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] 

回答

96

您可以使用交集方法&为:

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

很好和简单的解决方案谢谢。 – sayth 2012-04-19 14:44:49

+1

此方法也适用于两个以上的数组。不过,所有数组都必须包含所需的术语。 – Tommyixi 2015-03-23 23:49:42

+0

如果这些指数对于相同的值不相同,这将工作吗? – jacoballenwood 2017-07-13 22:55:04

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

OK,所以&运营商似乎是唯一你需要做得到这个答案。

但在此之前,我知道,我写了一个快速的猴子补丁的数组类要做到这一点:

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 

&操作是正确的答案,但。更优雅。

相关问题