From: "Jesús Gabriel y Galán" Date: 2012-07-02T16:52:53+09:00 Subject: Re: how to sort this nested hash On Mon, Jul 2, 2012 at 9:21 AM, yibin z. wrote: > s = {'s1'=>{'hn1'=>{'15'=> {'m1'=> ['aa', 'bb'] }}}, 's3'=>{'hn2'=>{'10' > => {'m2' => ['cc'] }}}, 's2'=>{'hn3'=>{'50'=> {'m3' => ['dd'] }}}} > > How to sort the above nested hash by keys like '15', '10', '50' shown > above? > > The result should look like: > > {'s2'=>{'hn3'=>{'50'=> {'m3' => ['dd']}}}, 's1'=>{'hn1'=>{'15'=> {'m1'=> > ['aa', 'bb'] }}}, 's3'=>{'hn2'=>{'10' => {'m2' => ['cc'] }}}} First of all, a Hash is not sorted, so the result cannot be what you typed. You can sort a Hash and store the result in somethins that is sorted, like an array. Next, you can use the method sort_by, which sorts an Enumerable object by the computation of the block you pass to it. Your structure is a bit complex, too much nesting there, but something like this could work: 1.9.2p290 :007 > s.sort_by{|k,v| tmp = v[v.keys.first]; - (tmp.keys.first).to_i} => [["s2", {"hn3"=>{"50"=>{"m3"=>["dd"]}}}], ["s1", {"hn1"=>{"15"=>{"m1"=>["aa", "bb"]}}}], ["s3", {"hn2"=>{"10"=>{"m2"=>["cc"]}}}]] Jesus.