"Mark", "date"=>"27/08/2015", "bed"=-6ren">
gpt4 book ai didi

ruby - 按嵌套值对哈希排序

转载 作者:太空宇宙 更新时间:2023-11-03 17:22:04 24 4
gpt4 key购买 nike

我的散列如下所示。我希望输出采用相同的哈希形式,但哈希根据价格排列。

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

我读过 How to sort a Ruby Hash by number value?但它只是一个嵌套的散列。我完全不知道如何实现这一目标。如果你们中有人愿意帮助我,我将不胜感激。

最佳答案

试试这个:

> 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" 这样的字符串,那么您可以删除逗号分隔符并将其转换为整数,例如:

> "15,000"
> "15,000".tr(',', '').to_i
#=> 15000

所以代码是这样的:

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

关于ruby - 按嵌套值对哈希排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32304710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com