在两个数组之间找到相同的值。

时间:2021-11-30 19:16:23

If I want to compare two arrays and create an interpolated output string if an array variable from array y exists in x how can I get an output for each matching element?

如果我想比较两个数组并创建一个插值输出字符串如果数组y中的数组变量存在于x中,我如何获得每个匹配元素的输出?

This is what I was trying but not quite getting the result.

这就是我所尝试的,但并没有得到结果。

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]

3 个解决方案

#1


100  

You can use the set intersection method & for that:

你可以使用集合相交法&为此:

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

#2


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}"

Will output:

将输出:

There are 2 numbers common in both arrays. Numbers are [2, 4]

#3


2  

OK, so the & operator appears to be the only thing you need to do to get this answer.

好的,所以&运算符似乎是得到这个答案所需要做的唯一的事情。

But before I knew that I wrote a quick monkey patch to the array class to do this:

但是在我知道我给数组类写了一个快速的monkey补丁之前:

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

The & operator is the correct answer here though. More elegant.

这里的&运算符是正确的答案。更优雅。

#1


100  

You can use the set intersection method & for that:

你可以使用集合相交法&为此:

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

#2


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}"

Will output:

将输出:

There are 2 numbers common in both arrays. Numbers are [2, 4]

#3


2  

OK, so the & operator appears to be the only thing you need to do to get this answer.

好的,所以&运算符似乎是得到这个答案所需要做的唯一的事情。

But before I knew that I wrote a quick monkey patch to the array class to do this:

但是在我知道我给数组类写了一个快速的monkey补丁之前:

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

The & operator is the correct answer here though. More elegant.

这里的&运算符是正确的答案。更优雅。