Skip to content

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

instance method

Enumerable#sort

() -> ::Array[Elem]
() { (Elem arg0, Elem arg1) -> ::Integer } -> ::Array[Elem]
sort → array
sort {|a, b| ... } → array

Returns an array containing the sorted elements of self. The ordering of equal elements is indeterminate and may be unstable.

With no block given, the sort compares using the elements’ own method <=>:

Example
%w[b c a d].sort              # => ["a", "b", "c", "d"]
{foo: 0, bar: 1, baz: 2}.sort # => [[:bar, 1], [:baz, 2], [:foo, 0]]

With a block given, comparisons in the block determine the ordering. The block is called with two elements a and b, and must return:

  • A negative integer if a < b.

  • Zero if a == b.

  • A positive integer if a > b.

Examples:

Example
a = %w[b c a d]
a.sort {|a, b| b <=> a } # => ["d", "c", "b", "a"]
h = {foo: 0, bar: 1, baz: 2}
h.sort {|a, b| b <=> a } # => [[:foo, 0], [:baz, 2], [:bar, 1]]

See also 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.3 · 3.2 · 3.1 · 3.0