ruby 查找两个数组之间的共同值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10230227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:02:35  来源:igfitidea点击:

Find values in common between two arrays

ruby

提问by sayth

If I want to compare two arrays and create an interpolated output string if an array variable from array yexists in xhow 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]

回答by Abe Voelker

You can use the set intersection method &for that:

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

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

回答by Simon Bagreev

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]

回答by boulder_ruby

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:

但在我知道我为数组类编写了一个快速的猴子补丁来做到这一点之前:

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.

&运营商是这里虽然正确答案。更优雅。