如何检查Ruby数组是否包含多个值之一?

我有两个Ruby数组,我需要看看它们是否有任何共同的值。 我可以循环遍历一个数组中的每个值,并在另一个数组中包含?(),但我确信有更好的方法。 它是什么? (这些数组都包含字符串。)

谢谢。

设置相交 :

a1 & a2 

这是一个例子:

 > a1 = [ 'foo', 'bar' ] > a2 = [ 'bar', 'baz' ] > a1 & a2 => ["bar"] > !(a1 & a2).empty? # Returns true if there are any elements in common => true 

有什么共同的价值? 你可以使用交叉算子: &

 [ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ] 

如果你正在寻找一个完整的交叉点(有重复),问题就更复杂了,这里已经有一个堆栈溢出: 如何返回一个带有重复元素的Ruby数组交集? (骰子系数中的双字母问题)

或者是一个快速片段 ,它定义“real_intersection”并validation以下测试

 class ArrayIntersectionTests < Test::Unit::TestCase def test_real_array_intersection assert_equal [2], [2, 2, 2, 3, 7, 13, 49] & [2, 2, 2, 5, 11, 107] assert_equal [2, 2, 2], [2, 2, 2, 3, 7, 13, 49].real_intersection([2, 2, 2, 5, 11, 107]) assert_equal ['a', 'c'], ['a', 'b', 'a', 'c'] & ['a', 'c', 'a', 'd'] assert_equal ['a', 'a', 'c'], ['a', 'b', 'a', 'c'].real_intersection(['a', 'c', 'a', 'd']) end end 

使用交集看起来不错,但效率很低。 我会用“任何?” 在第一个数组上(以便在第二个数组中找到其中一个元素时迭代停止)。 此外,使用第二个arrays上的Set将快速进行成员资格检查。 即:

 a = [:a, :b, :c, :d] b = Set.new([:c, :d, :e, :f]) c = [:a, :b, :g, :h] # Do a and b have at least a common value? a.any? {|item| b.include? item} # true # Do c and b have at least a common value? c.any? {|item| b.include? item} #false 

试试这个

 a1 = [ 'foo', 'bar' ] a2 = [ 'bar', 'baz' ] a1-a2 != a1 true