From: "ttanimichi (Tsukuru Tanimichi)" Date: 2022-07-19T02:41:32+00:00 Subject: [ruby-core:109239] [Ruby master Feature#12648] `Enumerable#sort_by` with descending option Issue #12648 has been updated by ttanimichi (Tsukuru Tanimichi). It's a lot of work to write `sort_by { -1 * _1.created_at.to_f }` when the target objects are `Time` instances. ```ruby ['foo', 'bar', 'baz'].map { search(_1) }.flatten.sort_by { -1 * _1.created_at.to_f } def search(query) client = Twitter::REST::Client.new do |config| config.consumer_key = "YOUR_CONSUMER_KEY" config.consumer_secret = "YOUR_CONSUMER_SECRET" config.access_token = "YOUR_ACCESS_TOKEN" config.access_token_secret = "YOUR_ACCESS_SECRET" end client.search(query, result_type: "recent").take(10) end ``` ``` $ ruby -e "-1 * Time.now" -e:1:in `*': Time can't be coerced into Integer (TypeError) from -e:1:in `
' ``` ---------------------------------------- Feature #12648: `Enumerable#sort_by` with descending option https://bugs.ruby-lang.org/issues/12648#change-98373 * Author: sawa (Tsuyoshi Sawada) * Status: Open * Priority: Normal ---------------------------------------- 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: