Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Array#sort_by!

array.sort_by! {|element| ... } → self
array.sort_by! → new_enumerator

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:

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

Returns a new Enumerator if no block given:

Example
a = ['aaaa', 'bbb', 'cc', 'd']
a.sort_by! # => #<Enumerator: ["aaaa", "bbb", "cc", "d"]:sort_by!>
See also #sort! #sum #sort #take also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0