如何在Ruby中按Total Points属性对Player对象列表排序?
按Total Points对Player对象列表排序的解决方案
问题背景
从API获取Player对象列表后,尝试按totalpoints排序时,以下两种写法均无效:
sorted = combo.sort_by(@totalpoints) sorted = combo.sort_by(:totalpoints)
错误原因
@totalpoints是当前上下文的实例变量,并非每个Player对象的属性,无法正确获取排序依据。sort_by方法直接传入符号:totalpoints不生效,Ruby需要将符号转换为Proc才能识别对象属性。
正确实现方式
1. 基础升序排序(从低分到高分)
写法一:使用块获取属性
sorted = combo.sort_by { |player| player.totalpoints }
写法二:符号转Proc的简洁写法
sorted = combo.sort_by(&:totalpoints)
2. 降序排序(从高分到低分)
如果需要按分数从高到低排列,有两种常用方式:
# 方式一:升序排序后反转 sorted_high_to_low = combo.sort_by(&:totalpoints).reverse # 方式二:直接通过sort方法比较 sorted_high_to_low = combo.sort { |a, b| b.totalpoints <=> a.totalpoints }
额外优化建议
你的代码中combo = Player.pull().map{|qb| qb}属于冗余写法,且Player.pull()返回的数组中包含nil值(因为map里的if条件过滤后会留下nil),建议修改为:
combo = Player.pull.compact # compact移除数组中的nil元素 sorted = combo.sort_by(&:totalpoints) puts sorted
内容的提问来源于stack exchange,提问作者ldthompson
相关产品推荐
相关产品推荐

