Search code examples
rubysortingenumerable

Why do I get "The error occurred while evaluating nil.<=>" when using sort_by?


This is the code:

xml = REXML::Document.new(data)
  @contacts = Array.new
  xml.elements.each('//entry') do |entry|
    person = {}
    person['name'] = entry.elements['title'].text

    gd_email = entry.elements['gd:email']
    person['email'] = gd_email.attributes['address'] if gd_email

    @contacts << person
  end

  @contacts.sort_by { |k| k['name'] } if @contacts[0].size > 0

the error:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.<=>

Solution

  • Try using:

    person['name'] = entry.elements['title'].text || ''
    

    instead of:

    person['name'] = entry.elements['title'].text