user3007294 user3007294 - 6 months ago 9
Ruby Question

Refactoring with OR operator in Ruby

This currently doesn't work. However, I believe the solution would be along these lines? I just need an error to be thrown if a coordinate is over 7.

class Game
def initialize(args={})
@dragon = args[:dragon] || [0,5]
@knight = args[:knight] || [1,3]
valid?
end

def valid?
raise ArgumentError, 'Please enter values between 0 and 7' unless ( ( (@dragon[0]) && (@dragon[1]) && (@knight[0]) && (@knight[1]) ) > 7 )
end
end


Thus, something like:

new_game = Game.new({dragon: [2,10], knight: [1,5]})


would throw an error.

Any ideas?

Thanks

Answer

You can do this:

valid = @dragon.concat(@knight).all? { |n| (0..7).include?(n) }

This irb session shows a case of success and failure for that test:

2.3.0 :009 > [2,10].concat([1,5]).all? { |n| (0..7).include?(n) }
 => false
2.3.0 :010 > [2,7].concat([1,5]).all? { |n| (0..7).include?(n) }
 => true