Class A has the following comparator:
class A
attr_accessor x
def my_comparator(a)
x**2 <=> (a.x)**2
end
end
I would like to use this comparator to sort an array where each item is of class A:
class B
def my_method
items.sort!(<how can I pass my_comparator here ?>)
end
end
How should I pass my_comparator to sort!?
Define your own
<=>, and include Comparable. This is from the Comparable doc: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
sortwith 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: