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 → new_array
array.sort {|a, b| ... } → new_array
array.c
View on GitHub ↗
VALUE
rb_ary_sort(VALUE ary)
{
ary = rb_ary_dup(ary);
rb_ary_sort_bang(ary);
return ary;
}
Returns a new Array whose elements are those from self, sorted.
With no block, compares elements using operator <=> (see Comparable):
Example
a = 'abcde'.split('').shuffle a # => ["e", "b", "d", "a", "c"] a1 = a.sort a1 # => ["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
bis to followa. -
Zero when
aandbare equivalent. -
Positive when
ais to followb.
Example:
Example
a = 'abcde'.split('').shuffle a # => ["e", "b", "d", "a", "c"] a1 = a.sort {|a, b| a <=> b } a1 # => ["a", "b", "c", "d", "e"] a2 = a.sort {|a, b| b <=> a } a2 # => ["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"] a1 = a.sort {|a, b| 0 } a1 # => ["c", "e", "b", "d", "a"]
Related: Enumerable#sort_by.