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

Array#sort!

array.sort! → self
array.sort! {|a, b| ... } → self

Returns self with its elements sorted in place.

With no block, compares elements using operator <=> (see Comparable):

Example
a = 'abcde'.split('').shuffle
a # => ["e", "b", "d", "a", "c"]
a.sort!
a # => ["a", "b", "c", "d", "e"]

With a block, calls the block with each element pair; for each element pair a and b, the block should return an integer:

  • Negative when b is to follow a.

  • Zero when a and b are equivalent.

  • Positive when a is to follow b.

Example:

Example
a = 'abcde'.split('').shuffle
a # => ["e", "b", "d", "a", "c"]
a.sort! {|a, b| a <=> b }
a # => ["a", "b", "c", "d", "e"]
a.sort! {|a, b| b <=> a }
a # => ["e", "d", "c", "b", "a"]

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

Example
a = 'abcde'.split('').shuffle
a # => ["e", "b", "d", "a", "c"]
a.sort! {|a, b| 0 }
a # => ["d", "e", "c", "a", "b"]
See also #sort #sort_by! #slice! #sum also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1