From: Tim Hunter Date: 2008-08-21T23:46:48+09:00 Subject: Re: hahses and sort Adam Akhtar wrote: > i have a hash whose values are hashes themselves like this > > stats_hash = > { > "fourth"=> {:total_completed=>1, :total_sold=>1, :str=>0.0}, > "third"=> {:total_completed=>1, :total_sold=>0, :str=>25.0}, > "second"=>{:total_completed=>1, :total_sold=>0, :str=>50.0}, > "first"=>{:total_completed=>1, :total_sold=>0, :str=>90.0} > } > > and I want to order the hash in decending order based on the the value > :str > > to give > > { > "first"=>{:total_completed=>1, :total_sold=>0, :str=>90.0}, > "second"=>{:total_completed=>1, :total_sold=>0, :str=>50.0}, > "third"=> {:total_completed=>1, :total_sold=>0, :str=>25.0}, > "fourth"=> {:total_completed=>1, :total_sold=>1, :str=>0.0} > } > Hashes are by definition unordered. The best you can do is make an array of the hash keys ordered the way you want them, then access the hash using the array. stats_hash = { "fourth"=> {:total_completed=>1, :total_sold=>1, :str=>0.0}, "third"=> {:total_completed=>1, :total_sold=>0, :str=>25.0}, "second"=>{:total_completed=>1, :total_sold=>0, :str=>50.0}, "first"=>{:total_completed=>1, :total_sold=>0, :str=>90.0} } keys = stats_hash.keys sorted_keys = keys.sort_by {|k| -stats_hash[k][:str]} puts sorted_keys -- Posted via http://www.ruby-forum.com/.