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

() -> ::Array[Elem]
() { (Elem a, Elem b) -> ::Comparable::_CompareToZero } -> ::Array[Elem]
() { (Elem a, Elem b) -> ::Comparable::_CompareToZero? } -> ::Array[Elem]
sort → new_array
sort {|a, b| ... } → new_array

Returns a new array containing the elements of self, sorted.

With no block given, compares elements using operator <=> (see Object#<=>):

Example
[0, 2, 3, 1].sort # => [0, 1, 2, 3]

With a block given, calls the block with each combination of pairs of elements from self; for each pair a and b, the block should return a numeric:

  • Negative when b is to follow a.

  • Zero when a and b are equivalent.

  • Positive when a is to follow b.

Example:

Example
a = [3, 2, 0, 1]
a.sort {|a, b| a <=> b } # => [0, 1, 2, 3]
a.sort {|a, b| b <=> a } # => [3, 2, 1, 0]

When the block returns zero, the order for a and b is indeterminate, and may be unstable.

See an example in Numeric#nonzero? for the idiom to sort more complex structure.

Related: see Methods for Fetching.

See also #sort! #slice! #slice #sort_by! also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0