I have a hash like this (it is the result of the group_by method):
{nil => [#<ActiveRecord id ..., ...], #<ActiveRecord ...> => [#<ActiveRecord id ..., ...], ...}
I need to sort it so that the nil
elements would be the first, and then all the other ActiveRecord
objects. How can I do this? Thanx
PS
I need only to sort the hash by the keys.
You cannot sort a hash, but :
Hashes enumerate their values in the order that the corresponding keys were inserted.
To get a specific key at the beginning, just make sure to insert it first. Here's an example:
array = [Integer, Range, BasicObject]
hash = array.group_by(&:superclass)
#=> {Numeric=>[Integer], Object=>[Range], nil=>[BasicObject]}
To get nil
first, create a hash with a nil
key and merge!
the new values:
hash = {nil => nil}
hash.merge!(array.group_by(&:superclass))
#=> {nil=>[BasicObject], Numeric=>[Integer], Object=>[Range]}
Assuming you have your hash in h
:
Hash[h.sort { |a,b|
NilClass === a.first ?
(NilClass === b.first ? 0 : -1) :
(NilClass === b.first ? 1 : a.first <=> b.first)
}]
Here we explicitly define sort
function, which will place nil
s in front, following by native ordering of other elements by keys ( ActiveRecord
instances in your case.)
Sidenote: you always can do sorting in database.
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.