简体   繁体   中英

Sorting array of hashes in ruby

How can I sort array of hashes if I have pre-determined order I have an array that needs to be sorted like this :

   array =  [{:attr_name=>:phone, :attr_value=>30}, {:attr_name=>:name, :attr_value=>20}, {:attr_name=>:similarity, :attr_value=>0}, {:attr_name=>:weight, :attr_value=>50}]

and I've got a hash based on which I want it to be sorted :

pre_sorted = {
            :name => 0,
            :phone => 1,
            :weight=> 2,
            :similarity => 3
        }

After sorting my array should look like this :

[{:attr_name=>:name, :attr_value=>20}, {:attr_name=>:phone, :attr_value=>30}, {:attr_name=>:weight, :attr_value=>50}, {:attr_name=>"similarity", :attr_value=>0}]

I've looked at the ruby sort and sort by docs and found related questions on So but couldn't figure it out because I'm just starting with rails.

To sort an array by a given criterion, you can use sort_by . In your case you want to sort by the entry in the pre_sorted hash, so:

array.sort_by do |hash|
  pre_sorted[ hash[:attr_name] ]
end

Array#sort接受用于比较的代码块: http : //www.ruby-doc.org/core-1.9.3/Array.html#method-i-sort

array.sort{|a,b| pre_sorted[a[:attr_value]] <=> pre_sorted[b[:attr_value]]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM