Skip to content

Instantly share code, notes, and snippets.

@knu
Created August 15, 2024 08:20
Show Gist options
  • Save knu/3ec2c034d7a4d66d0083041780e2dba2 to your computer and use it in GitHub Desktop.
Save knu/3ec2c034d7a4d66d0083041780e2dba2 to your computer and use it in GitHub Desktop.
Ruby tweak for reverse sorting
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