我有一系列哈希
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" }
]
我试图在以下基础上对数组哈希进行排序:gifted => "真&#34 ;.像这样
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" }
]
答案 0 :(得分:4)
arr.sort_by{|h| h[:gifted] == "true" ? 0 : 1}
答案 1 :(得分: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"}]