2014-03-12 167 views
0

我有散列其鍵哈希值排序陣列

arr = [ 
    { :tap=> "bucket", :mobile=> "charger", :apple=> "knife", :gifted => "true" }, 
    { :tap=> "bucket", :mobile=> "charger", :apple=> "knife" }, 
    { :tap=> "bucket", :mobile=> "charger", :apple=> "knife" }, 
    { :tap=> "bucket", :mobile=> "charger", :apple=> "knife", :gifted => "true" } 
] 

我嘗試的基礎上,陣列哈希排序的數組:優=>「真」。這樣

sorted = [ 
    { :tap=> "bucket", :mobile=> "charger", :apple=> "knife", :gifted => "true" }, 
    { :tap=> "bucket", :mobile=> "charger", :apple=> "knife", :gifted => "true" } 
    { :tap=> "bucket", :mobile=> "charger", :apple=> "knife" }, 
    { :tap=> "bucket", :mobile=> "charger", :apple=> "knife" } 
] 

回答

4
arr.sort_by{|h| h[:gifted] == "true" ? 0 : 1} 
+0

感謝,這是聰明的... – Prem

+0

你歡迎:) – aherve

1

根據您的實現,你也可以組這些項目

arr.group_by{|h| h[:gifted]} 
#=>=> {"true"=>[{:tap=>"bucket", :mobile=>"charger", :apple=>"knife", :gifted=>"true"}, {:tap=>"bucket", :mobile=>"charger", :apple=>"knife", :gifted=>"true"}], nil=>[{:tap=>"bucket", :mobile=>"charger", :apple=>"knife"}, {:tap=>"bucket", :mobile=>"charger", :apple=>"knife"}]} 

所以要得到真正的對象

arr.group_by{|h| h[:gifted]}["true"] 
#=>[{:tap=>"bucket", :mobile=>"charger", :apple=>"knife", :gifted=>"true"}, {:tap=>"bucket", :mobile=>"charger", :apple=>"knife", :gifted=>"true"}]