简体   繁体   中英

ruby how to find the source code to sort_by?

Does anyone know how to find the source code to the method sort_by used in Array Enumerable?

I've tried sort_by.source_location and get

 NameError: undefined local variable or method `sort_by' for main:Object

I've tried using pry but when I cd into the Array and then into Enumerable sort_by is not found.

You can always use the Ruby docs.

http://ruby-doc.org/core-2.0/Enumerable.html#method-i-sort_by

Hover over the method and there is a link at the top right to view the source.

In Pry , if you install the pry-doc plugin first, you should be able to view Enumerable#sort_by source.

The pry-doc plugin is required to expose C-level docs and source.

[13] pry(main)> $ Enumerable#sort_by

From: enum.c (C Method):
Owner: Enumerable
Visibility: public
Number of lines: 48

static VALUE
enum_sort_by(VALUE obj)
{
    VALUE ary, buf;
    NODE *memo;
    long i;
    struct sort_by_data *data;

    RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);

    if (RB_TYPE_P(obj, T_ARRAY) && RARRAY_LEN(obj) <= LONG_MAX/2) {
        ary = rb_ary_new2(RARRAY_LEN(obj)*2);
    }
    else {
        ary = rb_ary_new();
    }
    RBASIC(ary)->klass = 0;
    buf = rb_ary_tmp_new(SORT_BY_BUFSIZE*2);
    rb_ary_store(buf, SORT_BY_BUFSIZE*2-1, Qnil);
    memo = NEW_MEMO(0, 0, 0);
    OBJ_INFECT(memo, obj);
    data = (struct sort_by_data *)&memo->u1;
    data->ary = ary;
    data->buf = buf;
    data->n = 0;
    rb_block_call(obj, id_each, 0, 0, sort_by_i, (VALUE)memo);
    ary = data->ary;
    buf = data->buf;
    if (data->n) {
        rb_ary_resize(buf, data->n*2);
        rb_ary_concat(ary, buf);
    }
    if (RARRAY_LEN(ary) > 2) {
        ruby_qsort(RARRAY_PTR(ary), RARRAY_LEN(ary)/2, 2*sizeof(VALUE),
                   sort_by_cmp, (void *)ary);
    }
    if (RBASIC(ary)->klass) {
        rb_raise(rb_eRuntimeError, "sort_by reentered");
    }
    for (i=1; i<RARRAY_LEN(ary); i+=2) {
        RARRAY_PTR(ary)[i/2] = RARRAY_PTR(ary)[i];
    }
    rb_ary_resize(ary, RARRAY_LEN(ary)/2);
    RBASIC(ary)->klass = rb_cArray;
    OBJ_INFECT(ary, memo);

    return ary;
}
[14] pry(main)> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM