通过其中一个键值排序哈希

时间:2012-03-29 07:19:48

标签: ruby

我的@hash看起来像这样:

[1, {:clid=>1, :nvz=>4, :tip=>"IP", :name=>"Mark", :record=>"some text"}] 
[2, {:clid=>2, :nvz=>-5, :tip=>"AO", :name=>"Tom", :record=>"another text"}] 
[3, {:clid=>3, :nvz=>0, :tip=>"AO", :name=>"Pit", :record=>"another text"}] 

如何对此哈希进行排序,以便:nvz按顺序排序迭代,如下所示:

[2, {:clid=>2, :nvz=>-5, :tip=>"AO", :name=>"Tom", :record=>"another text"}] 
[3, {:clid=>3, :nvz=>0, :tip=>"AO", :name=>"Pit", :record=>"another text"}] 
[1, {:clid=>1, :nvz=>4, :tip=>"IP", :name=>"Mark", :record=>"some text"}] 

1 个答案:

答案 0 :(得分:3)

据我所知,原始哈希看起来像这样?

{
  1 => {:clid=>1, :nvz=>4, :tip=>"IP", :name=>"Mark", :record=>"some text"},
  2 => {:clid=>2, :nvz=>-5, :tip=>"AO", :name=>"Tom", :record=>"another text"},
  3 => {:clid=>3, :nvz=>0, :tip=>"AO", :name=>"Pit", :record=>"another text"}
}

如果是,请尝试此

@hash.sort_by{ |k,v| v[:nvz] }

<强> PS

至于你的原始哈希有NON INTEGER nvz('n')所以你应该将它转换为整数:

@hash.sort_by{ |k,v| v[:nvz].to_i }

<强> PPS

如果您需要将n排序为999

@hash.sort_by{ |k,v| v[:nvz] == 'n' ? 999 : v[:nvz] }