Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array element data[i][j][k] exists

Tags:

arrays

ruby

I need to find out if data[i][j][k] element exists, but I don't know if data[i] or data[i][j] not nil themselves.
If I just data[i][j][k].nil?, it throw undefined method [] for nil:NilClass if data[i] or data[i][j] is nil

So, I am using now

unless data[i].nil? or data[i][j].nil? or data[i][j][k].nil?
    # do something with data[i][j][k]
end

But it is somehow cumbersome.

Is there any other way to check if data[i][j][k] exists without data[i].nil? or data[i][j].nil? or data[i][j][k].nil? ?

like image 716
Qiao Avatar asked Sep 13 '25 21:09

Qiao


1 Answers

I usually do:

unless (data[i][j][k] rescue false)
    # do something
end
like image 122
pguardiario Avatar answered Sep 15 '25 13:09

pguardiario