Class A has the following comparator:
class A
attr_accessor x
def my_comparator(a)
x**2 <=> (a.x)**2
end
end
If you want to reuse these comparators in different places, it would be better to define them as a class, instead of rewriting the same lambda expression every time.
This is based on Java's implementation of Comparable interface:
module Comparator
def compare(a, b)
raise NotImplementedError, 'must implement this method'
end
def to_proc
->(a, b) { compare(a, b) }
end
end
class LengthComparator
include Comparator
def compare(a, b)
a.length <=> b.length
end
end
class ReverseLengthComparator < LengthComparator
def compare(a, b)
-super
end
end
You implement your comparison logic in the #compare method. You can then use this class like so: array.sort(&MyCustomComparator.new). It essentially boils down to a lambda expression, but supports more reusability in my opinion.