得到一个 Ruby 数组,如:
[ { "lat" => 123, "lon" => 456 },
{ "lat" => 789, "lon" => 102, "col" => "red" },
{ "lat" => 442, "lon" => 342 } ]
我想对其进行排序,以便将任何col
作为键的散列推到数组的顶部或底部。
无法找出正确的sort_by
语法/语义。
a = [ { "lat" => 123, "lon" => 456 },
{ "lat" => 789, "lon" => 102, "col" => "red" },
{ "lat" => 442, "lon" => 342 } ]
如果你想把它们放在顶部,那么
a.partition{|h| h.key?("col")}.flatten
如果你想把它们放在底部,那么按照铁皮人的建议,
a.partition{|h| h.key?("col").!}.flatten
我一直喜欢的更实用的方法:
require 'pp'
a = [ {:foo => "aa","col" => "bar"}, { "lat" => 123, "lon" => 456 },
{ "lat" => 789, "lon" => 102, "col" => "red" },
{ "lat" => 442, "lon" => 342 } ]
arr = a.group_by{|h| h.key?("col")}
pp arr[false] + arr[true] # on the bottom
输出:
[{"lat"=>123, "lon"=>456},
{"lat"=>442, "lon"=>342},
{:foo=>"aa", "col"=>"bar"},
{"lat"=>789, "lon"=>102, "col"=>"red"}]
pp arr[true] + arr[false] #on the top
输出:
[{:foo=>"aa", "col"=>"bar"},
{"lat"=>789, "lon"=>102, "col"=>"red"},
{"lat"=>123, "lon"=>456},
{"lat"=>442, "lon"=>342}]