Reputation: 2367
i have an array of hashes
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" }
]
I am trying to sort the array hashes on the basis of :gifted=> "true". like this
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" }
]
Upvotes: 0
Views: 53
Reputation: 29598
Depending on your implementation you could also group these items
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"}]}
so to get true objects
arr.group_by{|h| h[:gifted]}["true"]
#=>[{:tap=>"bucket", :mobile=>"charger", :apple=>"knife", :gifted=>"true"}, {:tap=>"bucket", :mobile=>"charger", :apple=>"knife", :gifted=>"true"}]
Upvotes: 1