How to sort a ruby array by two conditions

后端 未结 1 587
甜味超标
甜味超标 2021-01-21 16:07

I want to sort this array by two different conditionals.

First I want to sort the array by type: A type can be either (1,2,3,4) and I want to sort them in this order 4

1条回答
  •  温柔的废话
    2021-01-21 16:18

    This should do it:

    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] }
    

    output:

    #
    #
    #
    #
    #
    #
    

    0 讨论(0)
提交回复
热议问题