Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Array#sort
VALUE
rb_ary_sort(VALUE ary)
{
ary = rb_ary_dup(ary);
rb_ary_sort_bang(ary);
return ary;
}
Returns a new array containing the elements of self, sorted.
With no block given, compares elements using operator <=> (see Object#<=>):
[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
bis to followa. -
Zero when
aandbare equivalent. -
Positive when
ais to followb.
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.