2

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

5 Answers 5

7

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

Raganwald has one popular implementation.

Sign up to request clarification or add additional context in comments.

1 Comment

Looks like the answer. Mind waiting to see if anybody else has some other suggestion?
2

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

Comments

1

One alternative is to use an inline rescue:

boolean_array[day][slot].zero? rescue nil

Comments

0

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

Comments

0

You can do it without additional gems. Depending on what you have as the value, change to_i to to_f, etc.

if boolean_array[day].to_a[slot].to_i.zero?
  # boolean_array[day][slot] element exists
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.