Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Array#sort_by!

() { (Elem element) -> ::Comparable::_WithSpaceshipOperator } -> self
() { (Elem element) -> ::Comparable::_WithSpaceshipOperator? } -> self
() -> ::Enumerator[Elem, self]
sort_by! {|element| ... } → self
sort_by! → new_enumerator

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:

Example
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.

See also #sort! #sum #sort #take also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0