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
- Name = A [email protected]
- Name = B [email protected]
- Name = nil [email protected]
sort on this shud result in
- Name = A [email protected]
- Name = nil [email protected] - Name A wins over name nil
- 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