2013-08-01 51 views
2

我发现很难找到这个问题的答案。有人可以解释'&'在这种情况下的工作原理吗?

曾经有人告诉我如何找到数组中的共同元素:

> colours1 = %w(red green blue) 
> colours2 = %w(orange red black blue) 
> colours1 & colours2 
=> ["red", "blue"] 

但我不明白什么是“&”并不在此代码,它是如何找到共同的元素?

回答

2

要回答什么确实如此,我举the documentation of Array#&

交集 - 返回包含共同要素 两个数组,不包括任何重复的新数组。该订单从原始数组 保留。

至于如何这样做,我点你到rubinius implementation of Array#&

def &(other) 
    other = Rubinius::Type.coerce_to other, Array, :to_ary 

    array = [] 
    im = Rubinius::IdentityMap.from other 

    each { |x| array << x if im.delete x } 

    array 
end 

使用each { |x| array << x if im.delete x }仅在self(第一个数组)为元素被添加到返回的数组,如果它们包含在other阵列中。


请注意,C-红宝石实现的事情莫过于Rubinius的稍有不同或JRuby的做到这一点。但它应该让你知道发生了什么。

+0

那真棒。感谢您的详细解释。 –

2

因为它是这样定义的。 Array#&方法需要另一个数组并返回交集。

相关问题