Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to (better) check for element existence within multidimensional array?

Tags:

ruby

How do I avoid doing this?

if boolean_array[day] && boolean_array[day][slot] && boolean_array[day][slot].zero?
  # boolean_array[day][slot] element exists
end
like image 584
Alexandre Avatar asked Nov 21 '25 02:11

Alexandre


2 Answers

Basically, you want an andand method. You can then do if boolean_array[day].andand[slot].andand.zero?.

Raganwald has one popular implementation.

like image 189
Chuck Avatar answered Nov 25 '25 00:11

Chuck


I like Chuck's andand. I suppose you could also use the low-priority and to do it in plain Ruby, at least there would be no parens:

>> day = slot = 1; boolean_array = [[], [1,2]]

>> if t = boolean_array[day] and t = t[slot] and t = t.class
>>   puts t
>> end
Fixnum
like image 42
DigitalRoss Avatar answered Nov 24 '25 22:11

DigitalRoss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!