Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Enumerable#sort

enum.sort → array
enum.sort { |a, b| block } → array

Returns an array containing the items in enum sorted.

Comparisons for the sort will be done using the items’ own <=> operator or using an optional code block.

The block must implement a comparison between a and b and return an integer less than 0 when b follows a, 0 when a and b are equivalent, or an integer greater than 0 when a follows b.

The result is not guaranteed to be stable. When the comparison of two elements returns 0, the order of the elements is unpredictable.

Example
%w(rhea kea flea).sort           #=> ["flea", "kea", "rhea"]
(1..10).sort { |a, b| b <=> a }  #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

See also Enumerable#sort_by. It implements a Schwartzian transform which is useful when key computation or comparison is expensive.

See also #slice_when #sort_by #slice_before #sum also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1