Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 按其中一个键值对哈希进行排序_Ruby - Fatal编程技术网

Ruby 按其中一个键值对哈希进行排序

Ruby 按其中一个键值对哈希进行排序,ruby,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=>

我的
@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"}] 
[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"}] 
如何对该散列进行排序,使迭代按
:nvz
排序,如下所示:

[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"}] 
[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 => {: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

由于原始哈希已获得非整数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] }

这应该是一个数组吗?为什么在这些行的末尾没有逗号?我刚刚展示了每一行@散列看起来像这样{1=>{:clid=>1,:tip=>“IP”,:name=>“Mark”,:record=>“some text”,:nvz=>0},2=>{:clid=>2,:tip=>“OO”,:name=>“Tom”,:record=>“other text”,:nvz=>-10},3=>{:clid=>3,:tip=>“IP”,:name=>“b”,:record=>“和text”,:nvz=>4},4=>,:n=>,:nvz=>,,:notice=>“对不起,没有记录”,铁轨说:铁轨说:固定num与字符串的比较失败了:{1=>1,{1=>1,:tip=>“IP”,:名称=>“马克”,:记录=>“马克”,:记录=>,:铁轨说:铁轨说:对固定num与字符串的比较;铁轨说:对固定num与字符串的比较失败的字符串比较失败了:{1={1,{1=>1,{1.1=>1,{1.1.1=>1,:1.1.1.1.1.1.1.3,,,,,,:名名名名名=>“标记“,,,,,,,,,,,,,,,,,,,,,,,:名名名名名名名名名名名名为“,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,}所以在您的最后一行中,
nvz
等于
n
,那么您应该如何对数字和字符串进行排序?看我的更新,我的顺序是:0,-10,4,n。我需要:-10,0,4,n。我可以用999代替n