问题
My hash looks like below. I want the output to be in the same hash form but with hash arranged according to the 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 from How to sort a Ruby Hash by number value? but it is just with one nested hash. Totally clueless with how I could achieve that. Would be grateful if any of you are willing to help me.
回答1:
Try this:
> myhash.sort_by{|_,v| v["price"]}.to_h
#=>
{
4=>
{
"name"=>"Mark",
"date"=>"27/08/2015",
"bed"=>"3",
"furnish"=>"Fully",
"size"=>"10",
"price"=>710000
},
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
},
1=>
{
"name"=>"Mark",
"date"=>"27/08/2015",
"bed"=>"3",
"furnish"=>"Fully",
"size"=>"10",
"price"=>790000
}
}
Update:
If you have price in string like "15,000" then you can remove comma seprator and convert it to integer like:
> "15,000"
> "15,000".tr(',', '').to_i
#=> 15000
So code would be like:
> myhash.sort_by{|_,v| v["price"].tr(',', '').to_i}.to_h
回答2:
If your data (hash) is assigned to the variable h then you can sort it by price using this code:
h.sort_by {|key, value| value['price'].to_f}
It gives you an array of [key,value] pairs. To convert it back to hash, you can use:
Hash[h.sort_by {|key, value| value['price'].to_f}]
In recent versions of Ruby (2.1+) you can use to_h method as well.
Update:
Because you changed price to numeric value, to_f conversion is not required any more. So the final code looks like this:
h.sort_by {|key, value| value['price']}.to_h
来源:https://stackoverflow.com/questions/32304710/sort-hash-by-nested-value