Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Sorts the elements of self in place, using an ordering determined by the block; returns self.
Calls the block with each successive element; sorts elements based on the values returned from the block.
For duplicates returned by the block, the ordering is indeterminate, and may be unstable.
This example sorts strings based on their sizes:
a = ['aaaa', 'bbb', 'cc', 'd']
a.sort_by! {|element| element.size }
a # => ["d", "cc", "bbb", "aaaa"]
Returns a new Enumerator if no block given:
a = ['aaaa', 'bbb', 'cc', 'd']
a.sort_by! # => #<Enumerator: ["aaaa", "bbb", "cc", "d"]:sort_by!>
               static VALUE
rb_ary_sort_by_bang(VALUE ary)
    VALUE sorted;

    RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
    sorted = rb_block_call(ary, rb_intern("sort_by"), 0, 0, sort_by_i, 0);
    rb_ary_replace(ary, sorted);
    return ary;

Was this page useful?