在Ruby中对哈希数组进行排序

时间:2013-09-28 13:04:01

标签: ruby arrays sorting hash

我有一个哈希数组如下:

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

我想根据键"k2"对这个哈希数组进行排序。我希望按递减顺序对其进行排序,"-NA-"始终位于顶部。

我想要像这样的排序数组:

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

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

3 个答案:

答案 0 :(得分: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%"
  }
]

答案 1 :(得分: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-"视为最负数:minus Float :: INFINITY;使用三元运算符(if then else的简写),所有其他字符串的排序就像它们的负浮点表示一样。

答案 2 :(得分:1)

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

NA = "-NA-"
K2 = "k2" 
a.sort {|a,b| a[K2]==NA ? -1 : b[K2]==NA ? 1 : -a[K2].to_f <=> -b[K2].to_f }