Project

General

Profile

Feature #12648

`Enumerable#sort_by` with descending option

Added by sawa (Tsuyoshi Sawada) about 4 years ago. Updated about 3 years ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:76660]

Description

I would like to pass an optional argument to Enumerable#sort_by or Enumerable#sort_by! to allow descending sort. When the sort key is singular, this could be done by passing a single optinal boolean variable that represents ascending when false (default) and descending when true:

[3, 1, 2].sort_by(&:itself)        # => [1, 2, 3]
[3, 1, 2].sort_by(false, &:itself) # => [1, 2, 3]
[3, 1, 2].sort_by(true, &:itself)  # => [3, 2, 1]

When there are multiple sort keys, corresponding numbers of arguments should be passed:

[3, 1, 2, 0].sort_by{|e| [e % 2, e]}               # => [0, 2, 1, 3]
[3, 1, 2, 0].sort_by(false, false){|e| [e % 2, e]} # => [0, 2, 1, 3]
[3, 1, 2, 0].sort_by(false, true){|e| [e % 2, e]}  # => [2, 0, 3, 1]
[3, 1, 2, 0].sort_by(true, false){|e| [e % 2, e]}  # => [1, 3, 0, 2]
[3, 1, 2, 0].sort_by(true, true){|e| [e % 2, e]}   # => [3, 1, 2, 0]

Related issues

Related to Ruby master - Feature #15725: Proposal: Add Array#reverse_sort, #revert_sort!, #reverse_sort_by, and #reverse_sort_by!RejectedActions

Also available in: Atom PDF