How to access an element in an array of arrays without getting the "undefined" error

When you try to access an element in an array of arrays, the best way to avoid getting the error method <undefined `[] 'for nil: NilClass' if the element does not exist?

For example, I am doing this now, but it seems bad to me:

if @foursquare['response']['groups'][0].present? && @foursquare['response']['groups'][0]['items'].present?
+3
source share
3 answers

Depending on the contents of the array, you may omit .present?. Ruby will also just take on the last value in such a construction, so you can omit the statement if.

@foursquare['response']['groups'][0] &&
@foursquare['response']['groups'][0]['items'] &&
@foursquare['response']['groups'][0]['items'][42]

egonil ( post), andand gem ( ) Ruby 2.3 .

+3

Ruby 2.3.0 dig Hash, Array, (&.), .

@foursquare.dig('response', 'groups')&.first&.dig('items')

nil, .

+2
if @foursquare['response']['groups'][0].to_a['items']
  . . .

It happens that NilClassimplements #to_a, which returns [].This means that you can match each nilwith []and usually write one expression without tests.

+1
source

All Articles