2013-08-01 53 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#&方法需要另一個數組並返回交集。

相關問題