Mirror318 Mirror318 - 23 days ago 6
Ruby Question

Ruby—Nice way to chain lots of OR statements? (checking against array out-of-bounds)

I am doing a coding puzzle where you are a miner in an array, and you can't be out of bounds. I have this code:

if x > minemap.length-1 or x < 0 or y > minemap[0].length-1 or y < 0
return false
end


Is there a nicer/cleaner/one-thing-per-line way to chain lots of OR statements?

Answer

First off, use of or and and over || and && in conditions is not idiomatic in Ruby since they have different precedence and may not always do what you want (Style Guide reference). As for the actual question, something like this is more idiomatic Ruby:

(0...minemap.length).cover?(x) && (0...minemap[0].length).cover?(y)

This uses Range#cover? to check that x and y are inside the correct ranges and returns false unless that is true.