tags:

views:

60

answers:

4

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
+4  A: 

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

Raganwald has one popular implementation.

Chuck
Looks like the answer. Mind waiting to see if anybody else has some other suggestion?
Alexandre
+1  A: 

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
DigitalRoss
+1  A: 

One alternative is to use an inline rescue:

boolean_array[day][slot].zero? rescue nil
JRL
This is how I do it, too.
glenn mcdonald
A: 

if possible, initialize the days and that way you can do the check for boolean_array[day][slot].nil?

cgr