如何对数组或哈希进行排序,包括Rails中的哈希?

时间:2019-03-01 05:57:15

标签: ruby

我是新手。如何对我的哈希数组中的总线索进行排序。总销售线索最大值应该放在第一位。

Array  = [
  {
    "project_name"=>"Godrej United",
    "lead_stats"=>{ 
       "total_leads"=>1, 
       "untouched_leads"=>0, 
       "dumped_leads"=>1, 
       "not_responding"=>0, 
       "switched_off"=>0, 
       "hot_leads"=>1, 
       "cold_leads"=>1, 
       "warm_leads"=>0
     },
     "project_id"=>2
   },
   {
     "project_name"=>"Golden Panorama", 
     "lead_stats"=>{
       "total_leads"=>5, 
       "untouched_leads"=>0, 
       "dumped_leads"=>1, 
       "not_responding"=>0, 
       "switched_off"=>0, 
       "hot_leads"=>0, 
       "cold_leads"=>0, 
       "warm_leads"=>0
     }, 
     "project_id"=>10
   }
 ]

2 个答案:

答案 0 :(得分:1)

您对数组进行如下排序

Array.sort_by {|x|x['lead_stats']['total_leads']}.reverse

答案 1 :(得分:1)

您可以按照以下步骤进行操作

Array.sort_by {|x| -x['lead_stats']['total_leads'] }

替代答案如下,

Array.sort { |a,b| b['lead_stats']['total_leads'] <=> a['lead_stats']['total_leads'] }

以块替换ab以获得相反的顺序。