TicTacToe: Validating User Input using Ruby Blocks
With my TicTacToe game, there are several instances where user input is needed;
1. Decide on game type (Human vs Human, Computer vs Human, etc)
2. Decide on board size
3. Pick move (integer from 1-9 for 3x3 board)
I had coded 1 and 3 first, and initially had two very similar looking methods that had the following algorithm;
while true
input = get_user_input
break if valid?(input)
print invalid input message
When I had written the third method, it was the 3rd strike and refactoring had to be done. The only part of the algorithm that varied for each method was the valid() method, the rest was identical.
In Java 8 I would pass a predicate to perform the validation. In Ruby, blocks seem to be a quick and ideal solution for this kind of refactoring. I want to invoke a method but wrap a piece of functionality into a surrounding algorithm.
I was able to achieve this as follows;
def get_validated_user_input
while true
input = get_user_input
break if yield(input)
print_invalid_message
end
input
end
user_move = get_validated_user_input {|input| move_valid?(input, board)}
board_size = get_validated_user_input {|input| board_size_valid?(input, board_size_options)}