0

I am trying to ask a question and give back something depending on the answer. Here is my code:

X = 1
Y = 2
puts "x = 1 and y = 2"
puts "what is  x + y?"
user_input = gets.chomp
if user_input == 3
  print "Correct"
elsif user_input != 3
  print "Wrong"
end

It asks what 1+2 is, and if you input 3, it prints wrong, but if you input something else, it still replies back with wrong.

sawa
  • 165,429
  • 45
  • 277
  • 381
KayZ
  • 7
  • 2

1 Answers1

3

The issue is that gets will give you back user input as a string. When the user types 3, user_input becomes the string "3" and you are then comparing this to the integer 3. The two are not the same.

To fix, you'll need to convert the user input to an integer with to_i:

X = 1
Y = 2
puts "x = 1 and y = 2"
puts "what is x + y?"
user_input = gets.to_i

if user_input == 3
    print "Correct"
else
    print "Wrong"
end
lemonhead
  • 5,328
  • 1
  • 13
  • 25
  • `gets` (short for "get string") returns the string value of the user's input. [More info](http://stackoverflow.com/questions/23193813/how-does-gets-and-gets-chomp-in-ruby-work) – vich Aug 04 '15 at 20:54
  • A small point: `gets.to_i` is sufficient. You don't need to remove `\n` unless you're chomping at the bit to get rid of it. – Cary Swoveland Aug 05 '15 at 03:16
  • Thank you, now it works fine, but could you explain what is the difference between user_input = gets.chomp and user_input = gets.to_i. Please. – KayZ Aug 05 '15 at 23:03