Reputation: 139
Multiplication is the only operator that works. every other operator
still multiplies for some reason. for example, 5+5=25, 6-2=12, 6/2=12.
It looks as though all my operators are correct in the code, so I am
not quite sure why this is happening.
puts "Enter your first Number: "
first_num = gets.to_i
puts "Enter your modifier"
modifier = gets
puts "Enter second number"
second_num = gets.to_i
def add(first_num, second_num)
return first_num + second_num
end
def subtract(first_num, second_num)
return first_num - second_num
end
def multiply(first_num, second_num)
return first_num * second_num
end
def divide(first_num, second_num)
return first_num / second_num
end
case modifier
when +
final_num = add(first_num, second_num)
when -
final_num = subtract(first_num, second_num)
when *
final_num = multiply(first_num, second_num)
when %
final_num = divide(first_num, second_num)
end
puts final_num
Upvotes: 1
Views: 113
Reputation: 51
Put " "
around your operators
in your case statements.So case modifier when "+"
etc .gets saves things as a string
, so your modifier is saved as a string
.
Upvotes: 0
Reputation: 106802
gets
returns strings. More specifically gets
returns the string entered by the user including the line break which is appended when the user presses ENTER.
Therefore, it makes sense to first remove the new line from the user input with gets.chomp
. And second, compare modifier
with strings containing operators in the case
block:
puts "Enter your modifier"
modifier = gets.chomp
# ...
case modifier
when '+'
final_num = add(first_num, second_num)
when '-'
final_num = subtract(first_num, second_num)
when '*'
final_num = multiply(first_num, second_num)
when '%'
final_num = divide(first_num, second_num)
end
Or insted of the case
block a refactored version using a hash and send
:
OPS = { '+' => 'add', '-' => 'substract', '*' => 'multiply', '%' => 'divide' }
final_num = send(OPS[modifier], first_num, second_num)
Actually, I am surprised that Ruby doesn't raise a syntax error.
Upvotes: 3