Method: Enumerable#sort
- Defined in:
- enum.c
#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 #<=>:
%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:
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.
1384 1385 1386 1387 1388 |
# File 'enum.c', line 1384
static VALUE
enum_sort(VALUE obj)
{
return rb_ary_sort_bang(enum_to_a(0, 0, obj));
}
|