我的@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"}]
答案 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] }