How to pass a custom comparator to “sort”?

前端 未结 4 1668
一向
一向 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:51

    items.sort!(&:my_comparator)
    

    This calls the :my_comparator.to_proc internally, which returns a block

    proc {|x,y| x.my_comparator(y)}
    

    thus reducing this answer to Ben Alpert's answer.

    (But I agree with Phrogz's observation that if this is the natural order for the class, then you should use the Tin Man's answer instead.)

提交回复
热议问题