如何访问数组数组深处的元素而不获取“未定义方法”错误
当尝试访问数组数组深处的元素时,如果元素不存在,避免出现错误“undefined method `[]” for nil:NilClass”的最佳方法是什么?
例如,我目前正在这样做,但对我来说似乎很糟糕:
if @foursquare['response']['groups'][0].present? && @foursquare['response']['groups'][0]['items'].present?
When trying to access an element deep in an array of arrays, what is the best way to avoid getting the error 'undefined method `[]' for nil:NilClass' if an element doesn't exist?
For example I'm currently doing this, but it seems bad to me:
if @foursquare['response']['groups'][0].present? && @foursquare['response']['groups'][0]['items'].present?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Ruby 2.3.0 引入了一种名为
dig
的新方法 上的Hash
和Array
可以与新的安全导航运算符 (&.
) 结合使用来解决您的问题。如果任何级别缺少值,这将返回
nil
。Ruby 2.3.0 introduced a new method called
dig
on bothHash
andArray
that can be combined with the new safe navigation operator (&.
) to solve your problem.This will return
nil
if a value is missing at any level.根据您的数组内容,您可以省略
.present?
。 Ruby 也只会采用此类构造中的最后一个值,因此您可以省略if
语句。对于这个问题,更优雅的解决方案是 egonil (博客文章),andand gem (博客文章),甚至 Ruby 2.3 的 安全导航操作符。
更新:最近的Ruby包含
#dig
方法,在这种情况下可能会有所帮助。有关更多详细信息,请参阅 user513951 的回答。Depending on your array content, you can omit the
.present?
. Ruby will also just take the last value in such a construct, so you can omit theif
statement.More elegant solutions for this problem are the egonil (blog post), the andand gem (blog post), or even Ruby 2.3's safe navigation operator.
Update: Recent Rubies include the
#dig
method, which might be helpful in this case. See user513951's answer for more details.碰巧
NilClass
实现了一个返回[] 的
这意味着您可以将每个#to_a
。nil
映射到[]
并且通常编写单个表达式而不进行测试。It happens that
NilClass
implements a#to_a
that returns[].
This means that you can map everynil
to[]
and typically write a single expression without tests.