使用Ruby中的对象属性对对象列表进行排序 [英] Sort a list of objects by using their attributes in Ruby
问题描述
我有一个名为basket
的Fruit
结构列表.每个Fruit
结构都有一个name
(一个字符串)和一个calories
(一个整数).我想对basket
进行排序,以便:
I have a list of Fruit
structs called basket
. Each Fruit
struct has a name
(a string) and a calories
(an integer). I would like to sort basket
so that:
-
具有最高
calories
的Fruit
s首先出现.例如,卡路里为500的水果出现在卡路里为400的水果之前.
The
Fruit
s with the highestcalories
appear first. For example, a fruit with 500 calories appears before a fruit with 400 calories.
如果两个Fruit
具有相等的calories
,则忽略字母大小写,其name
首先出现的Fruit
排在前面.例如,给定两种水果具有相等的卡路里,一种叫做香蕉"的水果将排在一种叫做柑橘"的水果之前.
If two Fruit
s have equal calories
, the Fruit
whose name
comes first alphabetically comes first, ignoring case. For example, given two fruits with equal calories, one named "banana" will come before one named "Citrus".
Fruit
的定义不是我控制的,因此我更喜欢一种解决方案,该解决方案不涉及将任何内容混合到Fruit
中或对其进行更改.这可能吗?
The definition of Fruit
is not something I control so I'd prefer a solution which doesn't involve mixing anything into Fruit
or changing it. Is this possible?
推荐答案
简单的解决方法是
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
这篇关于使用Ruby中的对象属性对对象列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!