ifstatements or boolean expressions to control the return value of a method.
In our previous tic-tac-toe lab, we built a method,
#position_taken?, that checks to see if the user's submitted position is free or already filled with a token. This is a type of validation. Our
#position_taken? method protects our game from breaking when the user (accidentally or otherwise) submits a position that isn't available.
Our validation is still incomplete however. What if a user submits a position that isn't even on the board? A more complete validation might look something like this:
In this lab, you'll build a
#valid_move? method that accepts a board and an index to check and returns
true if the move is valid and
nil if not. A valid move means that the submitted position is:
We've already defined a method,
#position_taken? that handles the second part of our validation procedure (You'll have to re-define it in this lab or copy over the code you've already written). Consequently, we can call that method inside of our
#position_taken? method can thus be referred to as a helper method––a method that handles a discrete unit of behavior and is used inside of other methods to carry out a larger task.
#position_taken? method can be used directly in a conditional expression, for example:
def some_new_fabulous_method if position_taken? execute something else execute something else end end
This lab is test-driven, so run the test suite and use the output to help you solve this one. Here are a few things to keep in mind:
#valid_move?. By the time the user's selection reaches your
#valid_move?method, you may assume it has already been converted from the user's point of view (squares
9) to the array's point of view (squares
8, their input is invalid. There are a few different ways to check to see if a number is included in a range. Look up the
#between?method for starters.
true––that the position is on the board and that the position is not taken. Think about how to construct a method that must check two conditions. Can you use two
ifstatements? What about a boolean operator like
nilare considered to be "falsey". So, either a
nilreturn value for an invalid move will suffice.
View Validating Tic-tac-toe Input on Learn.co and start learning to code for free.