instance method
Array#sort
() -> ::Array[Elem]
() { (Elem a, Elem b) -> ::Integer } -> ::Array[Elem]
sort → new_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 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
bis to followa. -
Zero when
aandbare equivalent. -
Positive when
ais to followb.
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.