Ruby-on-rails rails - 查找多个数组之间的交集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3197412/
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-02 22:52:39  来源:igfitidea点击:

rails - Finding intersections between multiple arrays

ruby-on-railsrubyarraysarray-intersect

提问by Alex

I am trying to find the intersection values between multiple arrays.

我试图找到多个数组之间的交集值。

for example

例如

code1 = [1,2,3]
code2 = [2,3,4]
code3 = [0,2,6]

So the result would be 2

所以结果是 2

I know in PHP you can do this with array_intersect

我知道在 PHP 中你可以用 array_intersect 做到这一点

I wanted to be able to easily add additional array so I don't really want to use multiple loops

我希望能够轻松添加额外的数组,所以我真的不想使用多个循环

Any ideas ?

有任何想法吗 ?

Thanks, Alex

谢谢,亚历克斯

回答by Anurag

Use the &method of Arraywhich is for set intersection.

使用Array&方法,用于设置交集。

For example:

例如:

> [1,2,3] & [2,3,4] & [0,2,6]
=> [2]

回答by Fotios

If you want a simpler way to do this with an array of arrays of unknown length, you can use inject.

如果你想用一种更简单的方法来处理未知长度的数组,你可以使用注入。

> arrays = [code1,code2,code3]
> arrays.inject(:&)                   # Ruby 1.9 shorthand
=> [2]
> arrays.inject{|codes,x| codes & x } # Full syntax works with 1.8 and 1.9
=> [2]

回答by Marian13

Ruby 2.7 introduced Array#intersectionmethod to match the more succinct Array#&.

Ruby 2.7 引入了Array#intersection方法来匹配更简洁的Array#&

So, now, [1, 2, 3] & [2, 3, 4] & [0, 2, 6]can be rewritten in a more verbose way, e.g.

所以,现在,[1, 2, 3] & [2, 3, 4] & [0, 2, 6]可以用更详细的方式重写,例如

[1, 2, 3].intersection([2, 3, 4]).intersection([0, 2, 6])
# => [2]

[1, 2, 3].intersection([2, 3, 4], [0, 2, 6])
# => [2]