有谁知道如何找到Array Enumerable中使用的方法sort_by的源代码?
我尝试过sort_by.source_location并获取
NameError: undefined local variable or method `sort_by' for main:Object
我尝试过使用pry,但是当我进入数组然后进入Enumerable时,找不到sort_by。
答案 0 :(得分:4)
您始终可以使用Ruby文档。
http://ruby-doc.org/core-2.0/Enumerable.html#method-i-sort_by
将鼠标悬停在该方法上,右上方有一个链接即可查看来源。
答案 1 :(得分:2)
在Pry中,如果您先安装pry-doc
插件,则应该可以查看Enumerable#sort_by
来源。
pry-doc插件需要公开C级文档和源代码。
[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)>