为什么在使用sort_by时会出现“评估nil时发生的错误”?
-
09-10-2019 - |
题
这是代码:
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
错误:
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.<=>
解决方案
尝试使用:
person['name'] = entry.elements['title'].text || ''
代替:
person['name'] = entry.elements['title'].text
其他提示
最后一行不应该
@contacts.sort_by { |k| k['name'] } if @contacts.size > 0
不是 @contacts[0].size
?
另外,尝试添加一个 @contacts.compact!
在整理之前,以确保您没有 nil
数组中的值。
我认为您可以简化代码:
@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'] }
我没有您的XML样品来测试它,但是看起来应该可以使用。
如果是 element['title']
null是否会收到您看到的错误,因此您需要跳过这些元素或使用默认值对名称字段,例如“未知”。
不隶属于 StackOverflow