48

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]
4

3 回答 3

128

您可以为此使用设置交集方法&

x = [1, 2, 4]
y = [5, 2, 4]
x & y # => [2, 4]
于 2012-04-19T14:29:00.293 回答
17
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]
于 2012-04-19T14:33:29.393 回答
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

运营商在这里&是正确的答案。更优雅。

于 2014-04-18T18:50:34.657 回答