且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Ruby中的对象属性对对象列表进行排序

更新时间:2023-11-29 08:46:58

简单的解决方法是

basket.sort_by { |f| [-f.calories, f.name] }

当然,如果这是水果的标准排序顺序,则应该使用<=>方法并将Comparable模块与Fruit

Of course, if this is the canonical sort order for fruit then it should be defined using the <=> method and with the Comparable module mixed into Fruit