按嵌套值对哈希排序 [英] Sort hash by nested value

查看:117
本文介绍了按嵌套值对哈希排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的哈希如下所示.我希望输出为相同的哈希形式,但哈希是根据价格排列的.

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
  }
} 

我已阅读如何对Ruby哈希进行排序按数字值?,但这只是一个嵌套的哈希值.我对如何实现这一目标一无所知.如果您愿意帮助我,将不胜感激.

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.

推荐答案

尝试一下:

> 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
        }
    } 

更新:

如果您在字符串中使用价格,例如"15,000",则可以删除逗号分隔符并将其转换为整数,例如:

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

代码如下:

> myhash.sort_by{|_,v| v["price"].tr(',', '').to_i}.to_h

这篇关于按嵌套值对哈希排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆