2014-10-01 76 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; 
} 

这将检查两个阵列中的所有共享值。