如何根据Ruby中的一个键值对按降序对哈希行进行排序?

时间:2013-03-28 23:48:32

标签: ruby sorting hash

我有以下哈希:

lines[0] = {"a" => dog, "b" => 32, "c" =>555, "d" => 100}
lines[1] = {"a" => cat, "b" => 34, "c" =>554, "d" => 4542}
lines[2] = {"a" => bird, "b" => 31, "c" =>532435, "d" => 23}

我想按“b”按降序对散列进行排序,以便最终得到:

lines[0] = {"a" => cat, "b" => 34, "c" =>554, "d" => 4542}
lines[1] = {"a" => dog, "b" => 32, "c" =>555, "d" => 100}
lines[2] = {"a" => bird, "b" => 31, "c" =>532435, "d" => 23}

实现这一目标的最佳方法是什么? Ruby中是否有一种方法可以为您完成此任务?

3 个答案:

答案 0 :(得分:1)

lines.sort_by! {|hash| -hash["b"]}

答案 1 :(得分:1)

你似乎有一个奇特的情况,其中行不是数组而是哈希,所以你想根据值的顺序重新分配每个键的值,对于第一个从哈希创建的数组,排序,并根据新索引创建一个哈希,例如

lines = {}
lines[0] = {"a" => :dog, "b" => 32, "c" =>555, "d" => 100}
lines[1] = {"a" => :cat, "b" => 34, "c" =>554, "d" => 4542}
lines[2] = {"a" => :bird, "b" => 31, "c" =>532435, "d" => 23}

require 'pp'
pp Hash[lines.map.sort_by {|k,v| -v["b"]}.map.with_index {|v, index| [index, v[1]]}]

输出是:

{0=>{"a"=>:cat, "b"=>34, "c"=>554, "d"=>4542},
 1=>{"a"=>:dog, "b"=>32, "c"=>555, "d"=>100},
 2=>{"a"=>:bird, "b"=>31, "c"=>532435, "d"=>23}}

那说,为什么行是哈希?它可以更好地用数组表示

答案 2 :(得分:0)

你可以做到

lines.sort! { |a, b| b["b"] <=> a["b"] }