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 protected]
  2. Name = B [email protected]
  3. Name = nil [email protected]

sort on this shud result in

  1. Name = A [email protected]
  2. Name = nil [email protected] - Name A wins over name nil
  3. Name = B [email protected] - email [email protected] wins over name B

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

Pleas help.

Regards,
Sandeep G

On Sun, Jun 1, 2008 at 3:11 PM, Sandeep G. <
[email protected]> wrote:

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

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

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


Sessions by Collective Idea: Ruby on Rails training in a vacation
setting
http://sessions.collectiveidea.com

Thats a cool solution! Thanks Brandon!