2

得到一个 Ruby 数组,如:

[  { "lat" => 123, "lon" => 456 },
   { "lat" => 789, "lon" => 102, "col" => "red" },
   { "lat" => 442, "lon" => 342 } ]

我想对其进行排序,以便将任何col作为键的散列推到数组的顶部或底部。

无法找出正确的sort_by语法/语义。

4

2 回答 2

5
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
于 2013-04-22T06:08:17.757 回答
1

我一直喜欢的更实用的方法:

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}]
于 2013-04-22T07:16:35.540 回答