Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 获取状态时出错:未定义的方法`text';零级:零级_Ruby - Fatal编程技术网

Ruby 获取状态时出错:未定义的方法`text';零级:零级

Ruby 获取状态时出错:未定义的方法`text';零级:零级,ruby,Ruby,我对Ruby一无所知,在下面找到了报告AWS状态的代码 ruby-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) latest_status=x

我对Ruby一无所知,在下面找到了报告AWS状态的代码

ruby-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)
latest_status=xml_doc.css(“项目标题”).first.text
打印最新状态
在“`”中:nil:NilClass(NoMethodError)的未定义方法“text”

如果
第一个
出现空值并返回
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
您可能应该找出该选择器不起作用的原因,因为它可能不正确,最终什么也不返回。

可能与3小时前询问的标题几乎完全相同。
latest_status = xml_doc.css("item title").first
latest_status &&= latest_status.text