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.

2
  • 1
    What's your question? Commented Aug 4, 2015 at 20:46
  • @KayZ or someone with editing privileges, could you format the code correctly so it's easier to see where the line breaks are? Commented Aug 4, 2015 at 20:49

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

gets (short for "get string") returns the string value of the user's input. More info
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.