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

Hi,

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"]    end    if a["name"].nil?       n == 0 ? a["email"] <=> b["name"] :n    else       n == 0 ? a["name"] <=> b["email"]:n    end    n == 0 ? a["email"]<=> b["email"]:n

  end

1. Name = A email=Z@a.com 2. Name = B email=b@a.com 3. Name = nil email=a@c.com

sort on this shud result in 1. Name = A email=Z@a.com 3. Name = nil email=a@c.com - Name A wins over name nil 2. Name = B email=b@a.com - email a@c.com wins over name B

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

Pleas help.

Regards, 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

Brandon

Thats a cool solution! Thanks Brandon!