Reputation: 26212
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.
Upvotes: 2
Views: 1698
Reputation: 152
Array#sort accepts a block of code to use for the comparison: 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]]}
Upvotes: 1
Reputation: 370162
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
Upvotes: 5