使用Ruby中的对象属性对对象列表进行排序 [英] Sort a list of objects by using their attributes in Ruby

查看:81
本文介绍了使用Ruby中的对象属性对对象列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为basketFruit结构列表.每个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:

  1. 具有最高caloriesFruit s首先出现.例如,卡路里为500的水果出现在卡路里为400的水果之前.

  1. The Fruits with the highest calories appear first. For example, a fruit with 500 calories appears before a fruit with 400 calories.

如果两个Fruit具有相等的calories,则忽略字母大小写,其name首先出现的Fruit排在前面.例如,给定两种水果具有相等的卡路里,一种叫做香蕉"的水果将排在一种叫做柑橘"的水果之前.

If two Fruits 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆