Feature #8422
closed
add Enumerable#reverse_sort and Enumerable#reverse_sort_by
Added by Hanmac (Hans Mackowiak) over 11 years ago.
Updated over 11 years ago.
Description
they are better when you want descending order,
enum.sort.reverse
does work too, but it is to slow because it needs to build that result array twice
they both can be defined just like #sort and #sort_by but negates the result of the compare block
- Status changed from Open to Feedback
It can be done by a.sort{|a,b| b<=>a}
. Do we really need to define new methods?
Matz.
matz (Yukihiro Matsumoto) wrote:
It can be done by a.sort{|a,b| b<=>a}
.
That will typically be much slower though.
Currently, the best way to do a reverse sort, performance-wise, is a.sort.reverse!
For a random 100 number array, for example:
sort.reverse!
is faster than sort.reverse
by 10% ± 1.0%
sort.reverse
is faster than sort_by
by 6x ± 0.1
sort_by
is faster than sort
by 60% ± 1.0%
Code: https://gist.github.com/marcandre/5604592
-1, feature creep
But I'm for defining reverse!
as O(1), not really reversing anything, just treating the last element as first and first as last. (I do not know how collections are exactly implemented, so I am not sure whether this is possible.)
How do you sort an infinite Enumerable?
ruby -rprime -e 'p Prime.each.reverse_sort.take 10'
drbrain (Eric Hodel) wrote:
How do you sort an infinite Enumerable
?
ruby -rprime -e 'p Prime.each.reverse_sort.take 10
I'm not sure what your point is. How is that different from p Prime.each.sort.take 10
? Moreover, an alternative request could be to add Array#reverse_sort{_by}
.
Maybe we should consider a variation on sort
that allows multiple criteria and independent sort directions?
Neither Prime.each.reverse_sort.take 10
nor Prime.each.sort.take 10
will return as there is no last value for infinite streams. You can neither reverse nor sort an infinite stream.
I believe adding the feature to Enumerable
doesn't fit with its existing functionality (all beginning-of-stream oriented).
We need feedback from the submitter. Without it this issue should be closed.
drbrain (Eric Hodel) wrote:
Neither Prime.each.reverse_sort.take 10
nor Prime.each.sort.take 10
will return as there is no last value for infinite streams.
Of course. But you are aware that Enumerable
has a sort
method that acts as a shortcut to to_a.sort
?
We need feedback from the submitter. Without it this issue should be closed.
The relevant question here is "should there be a dedicated way to do a reverse sort". The question of where that method should be (Array
or Enumerable
) is accessory.
my idea would be this, for ruby it may be cood if its converted into C++ code
module Enumerable
def reverse_sort(&block)
block ||= proc {|x,y| x <=> y }
sort {|x,y| - block.call(x,y)}
end
def reverse_sort_by
return to_enum(__method__) unless block_given?
sort_by{|x| - yield(x)}
end
end
Also available in: Atom
PDF
Like0
Like0Like0Like0Like0Like0Like0Like0Like0