[英]Check hash for nil values
I'm trying to analyze tweets off of Twitter and one of the things I would like to include is the location.我正在尝试分析 Twitter 的推文,我想包括的其中一件事是位置。 Unfortunately, some of the values are nil and I keep getting the error不幸的是,有些值是零,我不断收到错误
undefined method `[]' for nil:NilClass (NoMethodError)
I would like to just run a check to see if the value is nil or not but I can't get anything to work.我只想运行一个检查,看看该值是否为零,但我什么也做不了。
The input would look like this if it is nil如果为 nil,输入将如下所示
tweet = {"metadata"=> {"geo"=>nil}}
and this if it has value如果它有价值
tweet = {"metadata"=> {"geo"=>{"coordinates"=>[0,1]}}
This is what I've tried这是我试过的
if "#{tweet['metadata']['geo']}".nil? == true
puts("nil")
else
puts("#{tweet['metadata']['geo']['coordinates']}"
end
What I've noticed is that it just checks to see if geo is empty because it outputs "nil" if I change the if statement to equal false.我注意到它只是检查 geo 是否为空,因为如果我将 if 语句更改为等于 false,它会输出“nil”。 I'm not sure how else to check我不确定如何检查
I think the problem may be that you're interpolating the hash in the string, which is converting the nil into an empty string, which is not actually nil. 我认为问题可能在于您要在字符串中插入哈希,这会将nil转换为空字符串,而实际上不是nil。
Try: 尝试:
if tweet['metadata']['geo'].nil?
puts("nil")
else
puts("#{tweet['metadata']['geo']['coordinates']}")
end
Using fetch on hash is a better way to Handle this type of problems. 在哈希上使用访存是处理此类问题的更好方法。 The below link to another answer shows how elegantly and beautifully this is handled. 以下指向另一个答案的链接显示了如何优雅而精美地处理该问题。 Ruby - Access multidimensional hash and avoid access nil object Ruby-访问多维哈希并避免访问nil对象
Use present?
使用present?
which checks for nil
and blank
as well. 也会检查nil
和blank
。 Check with following code. 检查以下代码。
if tweet['metadata']['geo'].present?
puts("nil")
else
puts("#{tweet['metadata']['geo']['coordinates']}")
end
In case anyone stumbles upon this, nowadays I'd suggest using dig
with safely returns nil if keys are not present.万一有人偶然发现了这一点,现在我建议使用dig
如果密钥不存在则安全地返回 nil 。
tweet = { "metadata" => { "geo"=> { "coordinates" => [0, 1] } } }
tweet.dig("metadata", "geo", "coordinates")
=> [0, 1]
missing_tweet = { "metadata" => { "geo" => nil } }
missing_tweet.dig("metadata", "geo", "coordinates")
=> nil
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.