2014-10-01 78 views
-2

爲什麼會出現這種情況?與&運算符匹配

words = ['molly', 'fish', 'sally'] 
cats = ['sally', 'molly'] 
matches = words & cats 

我的研究表明符號是一個按位運算符。爲什麼會有這種效果?

+1

爲什麼會有什麼影響? – 2014-10-01 21:15:45

+0

http://www.ruby-doc.org/core-2.1.1/Array.html#method-i-26 – xlembouras 2014-10-01 21:18:15

+0

[Fixnum @#&](http://www.ruby-doc.org/core- 2.1.1/Fixnum.html#method-i-26)是一個按位運算符; [Array#&](http://www.ruby-doc.org/core-2.1.1/Array.html#method-i-26)是數組相交。 '&''接收器在這裏('單詞')是一個fixnum還是一個數組? – 2014-10-01 21:21:57

回答

1

根據Array Ruby docs; #&是兩個數組之間的交集。

返回包含兩個數組通用元素的新數組,不包括任何重複項。訂單從原始數組中保留。

它使用它們的散列和eql比較元素?提高效率的方法。

0

&是返回交集的數組函數。

http://www.ruby-doc.org/core-2.1.3/Array.html#method-i-26

ary & other_ary → new_ary 
Set Intersection — Returns a new array containing elements common to the two arrays, excluding any duplicates. The order is preserved from the original array. 

It compares elements using their hash and eql? methods for efficiency. 

[ 1, 1, 3, 5 ] & [ 1, 2, 3 ]     #=> [ 1, 3 ] 
[ 'a', 'b', 'b', 'z' ] & [ 'a', 'b', 'c' ] #=> [ 'a', 'b' ] 
See also #uniq. 
2

Array上定義的方法稱爲:&

[] .class.method_defined?(:&)

=>真

這稱爲底層C代碼:

   static VALUE 
rb_ary_and(VALUE ary1, VALUE ary2) 
{ 
    VALUE hash, ary3, v; 
    st_table *table; 
    st_data_t vv; 
    long i; 

    ary2 = to_ary(ary2); 
    ary3 = rb_ary_new(); 
    if (RARRAY_LEN(ary2) == 0) return ary3; 
    hash = ary_make_hash(ary2); 
    table = rb_hash_tbl_raw(hash); 

    for (i=0; i<RARRAY_LEN(ary1); i++) { 
     v = RARRAY_AREF(ary1, i); 
     vv = (st_data_t)v; 
     if (st_delete(table, &vv, 0)) { 
      rb_ary_push(ary3, v); 
     } 
    } 
    ary_recycle_hash(hash); 

    return ary3; 
} 

這將檢查兩個陣列中的所有共享值。