Sort hash by nested value

雨燕双飞 提交于 2019-12-24 11:34:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!