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]
好的,因此&
操作员似乎是您获得此答案所需要做的唯一事情。
但在我知道我为数组类写了一个快速的猴子补丁来做到这一点之前:
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
运营商在这里&
是正确的答案。更优雅。