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
Post a Comment