我正在尝试寻找多个数组之间的交叉值。
例如
code1 = [1,2,3]
code2 = [2,3,4]
code3 = [0,2,6]
所以结果应该是2
我知道在PHP中你可以用array_intersect做到这一点。
我希望能够轻松地添加额外的数组,所以我不想使用多个循环
有什么想法吗?
谢谢,亚历克斯
发布于 2010-07-08 01:51:48
发布于 2013-02-13 03:50:48
如果您想用一种更简单的方法来处理长度未知的数组,可以使用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]
发布于 2020-04-14 06:16:01
Array#intersection (拼音2.7+)
为了匹配更简洁的Array#&,Ruby2.7引入了Array#intersection方法。
因此,现在可以用更冗长的方式重写[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]
https://stackoverflow.com/questions/3197412
复制相似问题