Issue #12648 has been updated by Greg L.


Nobuyoshi Nakada wrote:
> Greg L wrote:
> > Hence, a better solution might be adding a method like `sort_keys` or `sort_key`, where an array is returned by the block, and an array is used as the single parameter for ascending/descending info. 
> 
> Could you make clear what object these `sort_key`/`sort_keys` methods belong to?
> The array to be sorted?
> Or the returned object (it may not be an array) from the block?

I mentioned the fact that an array is often not returned by the block, hence, my suggestion for adding a new method.

Sorry, I should have shown a signature, below would be a possibility. The example shows three sort keys, 1st and 3rd are ascending, 2nd is descending.

`t = enum.sort_key([1, -1, 1]) { |x| [f(x), g(x), h(x)] }`

> Do you mean `enum.sort_by(-1) {...}` for descending?

Yes, but in an array, as above.  IOW, both the block return and the single parameter must be arrays.

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

* Author: Tsuyoshi Sawada
* Status: Open
* Priority: Normal
* Assignee: 
----------------------------------------
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>