Define your own <=>
, and include Comparable. This is from the Comparable doc:
class SizeMatters
include Comparable
attr :str
def <=>(an_other)
str.size <=> an_other.str.size
end
def initialize(str)
@str = str
end
def inspect
@str
end
end
s1 = SizeMatters.new("Z")
s2 = SizeMatters.new("YY")
s3 = SizeMatters.new("XXX")
s4 = SizeMatters.new("WWWW")
s5 = SizeMatters.new("VVVVV")
s1 < s2 #=> true
s4.between?(s1, s3) #=> false
s4.between?(s3, s5) #=> true
[ s3, s2, s5, s4, s1 ].sort #=> [Z, YY, XXX, WWWW, VVVVV]
You don't actually have to include Comparable, but you get extra functionality for free if you do that after having defined <=>
.
Otherwise, you can use Enumerable's sort
with a block if your objects implement <=>
already.
Another way to use several different comparisons is to use lambdas. This uses the new 1.9.2 declaration syntax:
ascending_sort = ->(a,b) { a <=> b }
descending_sort = ->(a,b) { b <=> a }
[1, 3, 2, 4].sort( & ascending_sort ) # => [1, 2, 3, 4]
[1, 3, 2, 4].sort( & descending_sort ) # => [4, 3, 2, 1]
foo = ascending_sort
[1, 3, 2, 4].sort( & foo ) # => [1, 2, 3, 4]