我一直在为此苦苦挣扎,无法获得令人满意的结果。我有这个哈希值:
{"idprj"=>13351, "prevInicioStr"=>"21/10/2019"}
{"idprj"=>14473, "prevInicioStr"=>"22/10/2019"}
{"idprj"=>14165, "prevInicioStr"=>"23/10/2019"}
{"idprj"=>14165, "prevInicioStr"=>"23/10/2019"}
{"idprj"=>14165, "prevInicioStr"=>"28/10/2019"}
{"idprj"=>14165, "prevInicioStr"=>"28/10/2019"}
{"idprj"=>14518, "prevInicioStr"=>"29/10/2019"}
{"idprj"=>14518, "prevInicioStr"=>"29/10/2019"}
{"idprj"=>13351, "prevInicioStr"=>"05/11/2019"}
{"idprj"=>14305, "prevInicioStr"=>"06/11/2019"}
{"idprj"=>14305, "prevInicioStr"=>"08/11/2019"}
{"idprj"=>14305, "prevInicioStr"=>"13/01/2020"}
我想按'prevInicioStr'进行排序,并按'idprj'进行分组(您可以看到ID 13351没有按应有的方式分组)。为了获得此结果,我这样做:
result.sort_by { |hash| [ Date.parse(hash['prevInicioStr']), hash['idprj'] ] }
答案 0 :(得分:2)
您必须先分组,然后再排序(实际上是对值进行排序):
data = [{"idprj"=>13351, "prevInicioStr"=>"21/10/2019"}, {"idprj"=>14473, "prevInicioStr"=>"22/10/2019"}, {"idprj"=>14165, "prevInicioStr"=>"23/10/2019"}, {"idprj"=>14165, "prevInicioStr"=>"23/10/2019"}, {"idprj"=>14165, "prevInicioStr"=>"28/10/2019"}, {"idprj"=>14165, "prevInicioStr"=>"28/10/2019"}, {"idprj"=>14518, "prevInicioStr"=>"29/10/2019"}, {"idprj"=>14518, "prevInicioStr"=>"29/10/2019"}, {"idprj"=>13351, "prevInicioStr"=>"05/11/2019"}, {"idprj"=>14305, "prevInicioStr"=>"06/11/2019"}, {"idprj"=>14305, "prevInicioStr"=>"08/11/2019"}, {"idprj"=>14305, "prevInicioStr"=>"13/01/2020"}]
pp data.group_by { |e| e['idprj'] }
.transform_values { |values| values.sort_by { |e| e['prevInicioStr'] } }
# {13351=>
# [{"idprj"=>13351, "prevInicioStr"=>"05/11/2019"},
# {"idprj"=>13351, "prevInicioStr"=>"21/10/2019"}],
# 14473=>[{"idprj"=>14473, "prevInicioStr"=>"22/10/2019"}],
# 14165=>
# [{"idprj"=>14165, "prevInicioStr"=>"23/10/2019"},
# {"idprj"=>14165, "prevInicioStr"=>"23/10/2019"},
# {"idprj"=>14165, "prevInicioStr"=>"28/10/2019"},
# {"idprj"=>14165, "prevInicioStr"=>"28/10/2019"}],
# 14518=>
# [{"idprj"=>14518, "prevInicioStr"=>"29/10/2019"},
# {"idprj"=>14518, "prevInicioStr"=>"29/10/2019"}],
# 14305=>
# [{"idprj"=>14305, "prevInicioStr"=>"06/11/2019"},
# {"idprj"=>14305, "prevInicioStr"=>"08/11/2019"},
# {"idprj"=>14305, "prevInicioStr"=>"13/01/2020"}]}