-
-
Save knu/3ec2c034d7a4d66d0083041780e2dba2 to your computer and use it in GitHub Desktop.
Ruby tweak for reverse sorting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Comparable | |
class Inverse | |
def initialize(value) | |
@value = value | |
end | |
attr_reader :value | |
def <=>(other) | |
other.is_a?(self.class) or raise TypeError, "Inverse can only be compared with Inverse" | |
other.value <=> value | |
end | |
end | |
def to_sort_desc | |
Inverse.new(self) | |
end | |
def to_sort_asc | |
self | |
end | |
end | |
pp [ | |
["B", "a"], | |
["B", "b"], | |
["A", "a"], | |
["A", "c"], | |
["A", "b"], | |
].sort_by { |x, y| [x, y.to_sort_desc] } | |
#=> [["A", "c"], ["A", "b"], ["A", "a"], ["B", "b"], ["B", "a"]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment