Issue #12648 has been updated by knu (Akinori MUSHA).


Another path could be to introduce a sense of "reversed object".

I don't yet have a good name for the method that wouldn't cause name clash, but here it goes.

```ruby
module Comparable
  class ReversedObject
    include Comparable

    def initialize(object)
      @object = object
    end

    attr_reader :object

    def <=>(other)
      other.object <=> object if other.instance_of?(self.class)
    end
  end

  def reversed
    ReversedObject.new(self)
  end
end

p ["aaa", "bbb", "ccc"].sort_by(&:reversed)
# ["ccc", "bbb", "aaa"]

require 'pp'
require 'time'

pp [
  ["banana", Date.parse("2017-10-03")],
  ["apple",  Date.parse("2017-10-03")],
  ["grape",  Date.parse("2017-10-02")],
  ["melon",  Date.parse("2017-10-02")],
  ["orange", Date.parse("2017-10-01")],
  ["cherry", Date.parse("2017-10-01")],
].sort_by { |name, date| [date, name.reversed] }
# [["apple", #<Date: 2017-10-03 ((2458030j,0s,0n),+0s,2299161j)>],
#  ["banana", #<Date: 2017-10-03 ((2458030j,0s,0n),+0s,2299161j)>],
#  ["grape", #<Date: 2017-10-02 ((2458029j,0s,0n),+0s,2299161j)>],
#  ["melon", #<Date: 2017-10-02 ((2458029j,0s,0n),+0s,2299161j)>],
#  ["cherry", #<Date: 2017-10-01 ((2458028j,0s,0n),+0s,2299161j)>],
#  ["orange", #<Date: 2017-10-01 ((2458028j,0s,0n),+0s,2299161j)>]]
```

----------------------------------------
Feature #12648: `Enumerable#sort_by` with descending option
https://bugs.ruby-lang.org/issues/12648#change-67071

* Author: sawa (Tsuyoshi Sawada)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
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`:

```ruby
[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:

```ruby
[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]
```




-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>