我对Ruby一无所知,在下面找到了报告AWS状态的代码
https://gist.github.com/ktheory/1604786
/1.rb https://status.aws.amazon.com/rss/a4b-us-east-1.rss
Error fetching status: undefined method `text' for nil:NilClass
红宝石-v ruby 2.5.1p57(2018-03-29修订版63029)[x86_64-linux]
latest_status = xml_doc.css("item title").first.text
print lastest_status
in `<main>': undefined method `text' for nil:NilClass (NoMethodError)
答案 0 :(得分:1)
如果first
空出并返回nil
,则您可能会犯错误,否则代码将崩溃。您需要谨慎行事:
latest_status = xml_doc.css("item title").first&.text
或者,如果您使用的是Ruby的旧版本,并且具有Rails的ActiveSupport:
latest_status = xml_doc.css("item title").first.try(:text)
否则,您将需要用困难的方式做到这一点:
latest_status = xml_doc.css("item title").first
latest_status &&= latest_status.text
您可能应该找出为什么该选择器不起作用的原因,因为它可能是不正确的,并且最终不返回任何内容。