Consider this array of hashes
array = [{:key0 => 'foo', :key1 => 'bar'},{:key0 => 'hot', :key1 => 'cold'}, ... ]
sort_by is the most compact form. To sort on :key0 in ascending order you write:
array.sort_by{ |a| a[:key0] }
sort is a little more verbose, but offers more flexibility:
array.sort{ |a, b| a[:key0] <=> b[:key0] }
If you want to sort strings in descending order then you switch the a and b assignments:
array.sort{ |a, b| b[:key0] <=> a[:key0] }
array.sort_by{ |a| [ a[:key0], a[:key1] }
But if you are using strings and you want one of the keys sorted in descending order then you need to use sort.
In this example the desired ordering is to first sort on :key0 in descending order and then on :key1 in ascending order:
array.sort do |a,b|
(b[:key0] <=> a[:key0]).nonzero? ||
(a[:key1] <=> b[:key1])
end
Not the most elegant or concise piece of code, but it does the job.
No comments:
Post a Comment