Project

General

Profile

Actions

Feature #12648

open

`Enumerable#sort_by` with descending option

Added by sawa (Tsuyoshi Sawada) over 8 years ago. Updated over 2 years ago.

Status:
Open
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 1 (0 open1 closed)

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

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0