How does Array#sort work when a block is passed?

前端 未结 7 1693
北海茫月
北海茫月 2020-11-29 18:10

I am having a problem understanding how array.sort{ |x,y| block } works exactly, hence how to use it?

An example from Ruby documentation:



        
7条回答
  •  北海茫月
    2020-11-29 18:47

    I believe |x,y| y<=>x is comparing two elements at a time in descending order, as seen in: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-3C-3D-3E Say with [ "d", "a", "e", "c", "b" ], "d" and "a" appear to be compared first. Then since it is descending, both remain in the same order because d evaluates to less than a. Then d and e are evaluated. "e" is moved to "d"'s position. Without knowing the internal workings of the c code it is not possible to know where is d moved to but I figure this process continues until all elements are sorted. The c functions:

               VALUE
    rb_ary_cmp(VALUE ary1, VALUE ary2)
    {
        long len;
        VALUE v;
    
        ary2 = rb_check_array_type(ary2);
        if (NIL_P(ary2)) return Qnil;
        if (ary1 == ary2) return INT2FIX(0);
        v = rb_exec_recursive_paired(recursive_cmp, ary1, ary2, ary2);
        if (v != Qundef) return v;
        len = RARRAY_LEN(ary1) - RARRAY_LEN(ary2);
        if (len == 0) return INT2FIX(0);
        if (len > 0) return INT2FIX(1);
        return INT2FIX(-1);
    }
    

提交回复
热议问题