开发者

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

How do I avoid doing this?

if boolean_array[day] && boolean_array[da开发者_开发技巧y][slot] && boolean_array[day][slot].zero?
  # boolean_array[day][slot] element exists
end


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

Raganwald has one popular implementation.


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


One alternative is to use an inline rescue:

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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜