2

我有一组哈希如下:

[{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v3", "k2"=>"5.1%"}]

我想根据key的"k2"对这个哈希数组进行排序。我想按降序对它进行排序,"-NA-"始终排在首位。

我想要这样的排序数组:

[{"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v3", "k2"=>"5.1%"}]

我尝试了 hash.sort_by 方法,但得到的结果不正确。如何在 Ruby 中做到这一点?

4

3 回答 3

4
a = [
  {"k1"=>"v1", "k2"=>"75.1%"},
  {"k1"=>"v2", "k2"=>"-NA-"},
  {"k1"=>"v3", "k2"=>"5.1%"}
]

na, rest = a.partition{|h| h["k2"] == "-NA-"}
na + rest.sort_by{|h| h["k2"].to_f}.reverse
# =>
[
  {
    "k1" => "v2",
    "k2" => "-NA-"
  },
  {
    "k1" => "v1",
    "k2" => "75.1%"
  },
  {
    "k1" => "v3",
    "k2" => "5.1%"
  }
]
于 2013-09-28T13:28:10.153 回答
1
ar = [{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v3", "k2"=>"5.1%"}]
ar.sort_by{|h|(k2 = h["k2"]) == "-NA-"? -Float::INFINITY : -k2.to_f}
#=>[{"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v3", "k2"=>"5.1%"}]

可以通过将浮点数作为负数来对浮点数进行降序排序。该块将被"-NA-"视为最大负数:减 Float::INFINITY;所有其他字符串都像它们的负浮点表示一样排序,使用三元运算符(的简写if then else)。

于 2013-09-28T14:09:05.320 回答
1

这是另一种(常用)方法(a来自@sawa):

NA = "-NA-"
K2 = "k2" 
a.sort {|a,b| a[K2]==NA ? -1 : b[K2]==NA ? 1 : -a[K2].to_f <=> -b[K2].to_f }
于 2013-09-28T20:59:30.037 回答