ruby - Sort hash by nested value -


my hash looks below. want output in same hash form hash arranged according price.

{   1=>{     "name"=>"mark",      "date"=>"27/08/2015",      "bed"=>"3",      "furnish"=>"fully",      "size"=>"10",      "price"=>790000   },    2=>{     "name"=>"mark",      "date"=>"27/08/2015",      "bed"=>"3",      "furnish"=>"fully",      "size"=>"10",      "price"=>720000   },    3=>{     "name"=>"mark",      "date"=>"27/08/2015",      "bed"=>"3",      "furnish"=>"fully",      "size"=>"10",      "price"=>750000   },    4=>{     "name"=>"mark",      "date"=>"27/08/2015",      "bed"=>"3",      "furnish"=>"fully",      "size"=>"10",      "price"=>710000   } }  

i've read how sort ruby hash number value? 1 nested hash. totally clueless how achieve that. grateful if of willing me.

if data (hash) assigned variable h can sort price using code:

h.sort_by {|key, value| value['price'].to_f}

it gives array of [key,value] pairs. convert hash, can use:

hash[h.sort_by {|key, value| value['price'].to_f}]

in recent versions of ruby (2.1+) can use to_h method well.

update:

because changed price numeric value, to_f conversion not required more. final code looks this:

h.sort_by {|key, value| value['price']}.to_h


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -