Jesus Jesus - 6 months ago 11
Ruby Question

My code does not work without that specific line. Why?

puts "Enter the first number"
num1 = Float(gets)

puts "Enter the second number"
num2 = Float(gets)

puts "Enter the operation"
op = gets
op = op.chomp # <--- THIS LINE!

case op
when "+" then puts num1 + num2
when "-" then puts num1 - num2
when "*" then puts num1 * num2
when "/" then puts num1 / num2
end

Answer

When entering the "+" operation, you hit two keys, + and return. Both produce a character, resulting in "+\n". (that \n is a newline character)

chomp removes the newline character.

Comments