ruby - 使用 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) }
解决方案
我用零?而不是空白?如果你愿意,你可以使用空白?和礼物?根据您的要求。排序可以如下进行
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]]
推荐阅读
- python - AttributeError:“类型”对象没有属性“_state”django
- javascript - 无法从对象中获取数据
- node.js - node.js: version of dependency (moment-timezone) changes at runtime
- c - 在 C linux 中创建子进程
- apostrophe-cms - Having issues with permissions on Apostrophe production
- angular - angular 4 如何打开默认 div
- node.js - 如何使用nodejs和hapi@8.8.1上传和处理csv文件
- apache-spark - 如何在pyspark中读取坐标矩阵并将其写入文件
- swift - 使用带有for循环的presentingViewController返回
- neo4j - 使用 neo4j 的 Cypher 如何找到最大组直径为 3 的断开连接的节点组