How to pass a custom comparator to “sort”?

前端 未结 4 1675
一向
一向 2020-12-25 12:42

Class A has the following comparator:

class A
  attr_accessor x

  def my_comparator(a)
    x**2 <=> (a.x)**2
  end
end

4条回答
  •  没有蜡笔的小新
    2020-12-25 12:46

    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.

提交回复
热议问题