首页 > 解决方案 > 使用 SORT_BY 将数组排序为 4 组

问题描述

我有一个二维数组,我需要使用 sort_by 对这些数组中的值进行排序!(例如,当数组的第二个值为 nil 时,它属于第一组)

我用每种方法都这样做了,但我需要一个更漂亮/可读的代码。

到目前为止我所拥有的:arry 模式:[[164, nil, 6], [163, nil, 6], [162, nil, 6], [161, nil, 7], [160, "FSDL", 6 ]]

        matches.each do |match|
          first_group << match.first if match.second.blank? && match.last == 6
          second_group << match.first if match.second.present? && match.last == 6
          third_group << match.first if  match.last == 4
          forth_group << match.first if  match.last == 7
        end

return first_group + second_group + third_group + forth_group

我想做这样的事情:

match.sort_by!{ |比赛| (match.second == nil && match.last == 6)(second_condition) (third_condition) (fourth_condition) }

标签: ruby

解决方案


我用零?而不是空白?如果你愿意,你可以使用空白?和礼物?根据您的要求。排序可以如下进行

matches.sort_by do |match|
    if(match[1].nil? && match.last == 6)
        "1 #{match.first}"
    elsif(not match[1].nil? && match.last == 6)
        "2 #{match.first}"
    elsif(match.last == 4)
        "3 #{match.first}"
    elsif(match.last == 7)
        "4 #{match.first}"
    else
        "5 #{match.first}"
    end
end

使用上面的代码,如果任何不符合条件的内容将附加到最后

它将为给定的样本产生以下输出

[[162, nil, 6], [163, nil, 6], [164, nil, 6], [160, "FSDL", 6], [161, nil, 7]]

推荐阅读