80

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

例如

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

所以结果是 2

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

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

有任何想法吗 ?

谢谢,亚历克斯

4

3 回答 3

125

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

例如:

> [1,2,3] & [2,3,4] & [0,2,6]
=> [2]
于 2010-07-07T17:51:48.283 回答
53

如果你想要一个更简单的方法来处理未知长度的数组,你可以使用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]
于 2013-02-12T19:50:48.157 回答
2

Array#intersection (Ruby 2.7+)

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

所以,现在,[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]
于 2020-04-13T22:16:01.473 回答