[英]Sort an array in 4 groups with SORT_BY
我有一个2D数组,我需要使用sort_by按这些数组中的值排序! (例如,当数组的第二个值为nil时,它属于第一个组)
我用每种方法完成了这个,但我需要一个更漂亮/可读的代码。
到目前为止我所拥有的:arry pattern:[[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
我想做这样的事情:
matches.sort_by! {|匹配| (match.second == nil && match.last == 6)(second_condition)(third_condition)(fourth_condition)}
我用的是nil? 而不是空白? 如果你想要你可以使用空白? 和礼物? 根据您的要求。 排序可以如下完成
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]]
没有完全清楚预期的输出,但如果这返回它,我将添加一个解释。
matches = [[164, nil, 6], [163, nil, 6], [162, nil, 6], [161, nil, 7], [160, "FSDL", 6] ]
matches.group_by(&:last).tap { |h| h[6] = h[6].group_by { |e| e[1].nil? } }
.tap { |h| h.default = [] }
.then { |h| h[6][true] + h[6][false] + h[4] + h[7] }
.map(&:first)
#=> [164, 163, 162, 160, 161]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.