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

StackOverflow https://stackoverflow.com/questions/4380785

  •  09-10-2019
  •  | 
  •  

Pergunta

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.<=>
Foi útil?

Solução

Try using:

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

instead of:

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

Outras dicas

Shouldn't the last line be

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

not @contacts[0].size ?

Also, try adding a @contacts.compact! before sorting to ensure you have no nil values in the array.

I think you can streamline your code a bit:

@contacts = Array.new
xml = REXML::Document.new(data)
xml.elements.each('//entry') do |entry|
  gd_email = entry.elements['gd:email']

  @contacts << {
    'name'  => entry.elements['title'].text,
    'email' => (gd_email) ? gd_email.attributes['address'] : '' 
  }
end

@contacts.sort_by! { |k| k['name'] }

I don't have samples of your XML to test it, but it looks like it should work.

If the element['title'] is null you'll get the error you are seeing so you'll want to either skip those elements or use a default value for the name field, like "unknown".

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top