2012-04-19 62 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 

&操作是正確的答案,但。更優雅。