Mirror318 Mirror318 - 1 year ago 72
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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download