Method: Array#sort_by!

Defined in:
array.c

#sort_by! {|element| ... } ⇒ self #sort_by!Object

With a block given, sorts the elements of self in place; returns self.

Calls the block with each successive element; sorts elements based on the values returned from the block:

a = ['aaaa', 'bbb', 'cc', 'd']
a.sort_by! {|element| element.size }
a # => ["d", "cc", "bbb", "aaaa"]

For duplicate values returned by the block, the ordering is indeterminate, and may be unstable.

With no block given, returns a new Enumerator.

Related: see Methods for Assigning.

Overloads:

  • #sort_by! {|element| ... } ⇒ self

    Yields:

    • (element)

    Returns:

    • (self)


3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
# File 'array.c', line 3603

static VALUE
rb_ary_sort_by_bang(VALUE ary)
{
    VALUE sorted;

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