如果我想比較兩個數組並創建一個插值輸出字符串,如果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]
如果我想比較兩個數組並創建一個插值輸出字符串,如果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]
您可以使用交集方法&
爲:
x = [1, 2, 4]
y = [5, 2, 4]
x & y # => [2, 4]
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]
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
的&
操作是正確的答案,但。更優雅。
很好和簡單的解決方案謝謝。 – sayth 2012-04-19 14:44:49
此方法也適用於兩個以上的數組。不過,所有數組都必須包含所需的術語。 – Tommyixi 2015-03-23 23:49:42
如果這些指數對於相同的值不相同,這將工作嗎? – jacoballenwood 2017-07-13 22:55:04