我有一个复杂的嵌套散列数组。我试图测试一个特定元素是否为空。检查数组元素是否存在
以下方法在控制台上返回NoMethodError:。 empty?
,.nil?
,.blank?
这里是阵列(有点格式化)
{
"query" =>"ominous",
"sourceLanguage" =>"en",
"targetLanguage" =>"en",
"primaries" => [
{
"type" =>"headword",
"terms" => [
{
"type" =>"text",
"text" =>"om·i·nous",
"language" =>"en",
"labels" => [
{
"text" =>"Adjective",
"title" =>"Part-of-speech"
}
]
},
{
"type" =>"phonetic",
"text" =>"/ˈämənəs/",
"language" =>"und"
},
{
"type" =>"sound",
"text" =>"http://www.gstatic.com/dictionary/static/sounds/de/0/ominous.mp3",
"language" =>"und"
}
],
"entries" => [
{
"type" =>"meaning",
"terms" => [
{
"type" =>"text",
"text" =>"Giving the impression that something bad or unpleasant is going to happen; threatening; inauspicious",
"language" =>"en"
}
],
"entries" => [
{
"type" =>"example",
"terms" => [
{
"type" =>"text",
"text" =>"there were x3cemx3eominousx3c/emx3e dark clouds gathering overhead",
"language" =>"en"
}
]
}
]
}
]
}
]
}
因此,例如,我知道一个特定的元素是空的(或不存在),但使用任何的时以上三种方法来测试这个,我得到一个NoMethodError。
例子:
2.1.0 :034 > result["primaries"][0]["entries"][0]["terms"][0]["text"]
=> "Giving the impression that something bad or unpleasant is going to happen; threatening; inauspicious"
2.1.0 :035 > result["primaries"][0]["entries"][0]["terms"][0]["text"].empty?
=> false
现在,我知道下一个元素是空的(不存在),所以我用:
2.1.0 :036 > result["primaries"][0]["entries"][1]["terms"][0]["text"].empty?
NoMethodError: undefined method `[]' for nil:NilClass
from (irb):36
from /home/kyle/.rvm/gems/ruby-2.1.0/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start'
from /home/kyle/.rvm/gems/ruby-2.1.0/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start'
from /home/kyle/.rvm/gems/ruby-2.1.0/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
我也看到了.include?
或.in?
检查文字值的方法,但我想检查元素是否存在任何数据。
所以这个值可以是一个哈希,数组或字符串,并且您正在寻找这些空的地方? – Matt
为了让我们能够测试我们的反应,如果您可以提供我们可以加载的东西(上面的数组似乎损坏了),那将是非常好的。你介意提供数组的yaml转换吗? '要求'yaml''和'把yourarray.to_yaml'。与我们分享输出=) – Abdo
我并不意味着重要,但为了您自己的利益,可能需要重新评估您的数据结构。 – squiguy