I'm refactgoring a learning game for kids to learn spelling and math. I'm trying to expand the math by multiplication, subtraction and division operators.
The problem occurs when the process loopes for a long time, because I don't want it to return a negative number.
Brief process description: The two numbers for selected operator are generated randomly from ranges (currently 0..9). The computation executes and if the result is a negative number the whole process runs again.
The problem of course occurs only with subtraction and division.
Sources:
loop code: lines 82 to 85 in https://github.com/sebastjan-hribar/abc123/blob/master/lib/abc123.rb
helpers: https://github.com/sebastjan-hribar/abc123/blob/master/lib/abc123/helpers_math.rb
My question?
Is there a more elegant way of implementing these calculations to avoid the result often being a negative number (maybe by predefining the numbers to be used as input1 and input2)?
The addition runs ok, but with subtraction it often loops w/o end.
Maybe instead of while and stuff you should do something like this:
def compute(operator)
input_1, input_2 = prepare_arguments(operator)
result = case operator
when "add"
input_1 + input_2
when "multiply"
input_1 * input_2
when "subtract"
input_1 - input_2
when "divide"
input_1 / input_2
end
{result: result, operator: operator, input_1: input_1, input_2: input_2}
end
def prepare_arguments(operator)
case operator
when "subtract"
[first_argument = rand(0..9), first_argument + rand(0..9)].reverse
when "divide"
[first_argument = rand(1..9), first_argument * rand(0..9)].reverse
else
[rand(0..9), rand(0..9)]
end
end
So if you have an operator it will result with correct arguments and the result of computation.