Sorting an array of Hash on two fields one of it is optional


I need to sort an array of Hash - an array whose elements are hash
variable - a hash of name and email. Name is an optional field , ie it
can be nil but email is always not NULL.

How do I sort the array of these hash variables? SOrt on names. But if
name is nil, then sort on emailID.

@contacts = @my_contacts.sort! do |a,b|

         if a["name"] != nil && b["name"] != nil
       n = a["name"] <=> b["name"]
   if a["name"].nil?
      n == 0 ? a["email"] <=> b["name"] :n
      n == 0 ? a["name"] <=> b["email"]:n
   n == 0 ? a["email"]<=> b["email"]:n


1. Name = A
2. Name = B
3. Name = nil

sort on this shud result in
1. Name = A
3. Name = nil - Name A wins over name nil
2. Name = B - email wins over name B

But i am getting comparision of hash and hash failed - Error.

Pleas help.

Sandeep G

I would just do:

@contacts = @my_contacts.sort_by {|c| “#{c[:name]}#{c[:email]}” }

This sorts by a new string that is the combination of the name and email. If the name is nil, nothing will be inserted and it will just have the email


Thats a cool solution! Thanks Brandon!