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?
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 theifstatement.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
#digmethod, which might be helpful in this case. See user513951‘s answer for more details.