【问题标题】:How to sort a ruby array by two conditions如何按两个条件对 ruby​​ 数组进行排序
【发布时间】:2015-07-03 13:27:08
【问题描述】:

我想按两个不同的条件对该数组进行排序。

首先我想按类型对数组进行排序:类型可以是 (1,2,3,4),我想按 4 - 1 - 2 - 3 的顺序对它们进行排序。

然后在每种不同的类型中,我想按百分比降序对它们进行排序。

所以排序后的数组应该是这样的:

[
  <OpenStruct percent=70, type=4>,
  <OpenStruct percent=60, type=4>,
  <OpenStruct percent=50, type=4>,
  <OpenStruct percent=73, type=1>,
  <OpenStruct percent=64, type=1>,
  <OpenStruct percent=74, type=2>
]ect

我怎样才能完成这种排序?目前我只能按类型降序排序。

array = array.sort_by {|r| r.type }

【问题讨论】:

  • 为什么要 4 个先行?重命名类型并将 4 更改为 1 是否有意义,如果 4 应该始终排在第一位?

标签: ruby arrays sorting


【解决方案1】:

应该这样做:

require 'ostruct'
arr = [
  OpenStruct.new(percent: 73, type: 1),
  OpenStruct.new(percent: 70, type: 4),
  OpenStruct.new(percent: 60, type: 4),
  OpenStruct.new(percent: 50, type: 4),
  OpenStruct.new(percent: 64, type: 1),
  OpenStruct.new(percent: 74, type: 2)
]


puts arr.sort_by { |a| [a.type % 4, -a.percent] }

输出:

#<OpenStruct percent=70, type=4>
#<OpenStruct percent=60, type=4>
#<OpenStruct percent=50, type=4>
#<OpenStruct percent=73, type=1>
#<OpenStruct percent=64, type=1>
#<OpenStruct percent=74, type=2>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-02
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多