Skip to content

Instantly share code, notes, and snippets.

@banister
Created June 25, 2012 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save banister/2986330 to your computer and use it in GitHub Desktop.
Save banister/2986330 to your computer and use it in GitHub Desktop.
[10] (pry) main: 0> show-source Array#sort_by
From: enum.c (C Method):
Number of lines: 31
Owner: Enumerable
Visibility: public
static VALUE
enum_sort_by(VALUE obj)
{
VALUE ary;
long i;
RETURN_ENUMERATOR(obj, 0, 0);
if (TYPE(obj) == T_ARRAY) {
ary = rb_ary_new2(RARRAY_LEN(obj));
}
else {
ary = rb_ary_new();
}
RBASIC(ary)->klass = 0;
rb_block_call(obj, id_each, 0, 0, sort_by_i, ary);
if (RARRAY_LEN(ary) > 1) {
ruby_qsort(RARRAY_PTR(ary), RARRAY_LEN(ary), sizeof(VALUE),
sort_by_cmp, (void *)ary);
}
if (RBASIC(ary)->klass) {
rb_raise(rb_eRuntimeError, "sort_by reentered");
}
for (i=0; i<RARRAY_LEN(ary); i++) {
RARRAY_PTR(ary)[i] = RNODE(RARRAY_PTR(ary)[i])->u2.value;
}
RBASIC(ary)->klass = rb_cArray;
OBJ_INFECT(ary, obj);
return ary;
}
[12] (pry) main: 0> show-doc Array#sort
From: array.c (C Method):
Number of lines: 9
Owner: Array
Visibility: public
Signature: sort()
Returns a new array created by sorting self. Comparisons for
the sort will be done using the <=> operator or using
an optional code block. The block implements a comparison between
a and b, returning -1, 0, or +1. See also
Enumerable#sort_by.
a = [ "d", "a", "e", "c", "b" ]
a.sort #=> ["a", "b", "c", "d", "e"]
a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
[13] (pry) main: 0>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment