0

I am VERY new to Ruby. I was trying to make a simple "How's your day?" kind of thing, but when I answer with "Good" it's supposed to return "Good to hear" but it skips it and goes to my else statement that returns "Not valid". Same thing when I enter "Bad", it's supposed to give me "Oh no" but instead it gives me "Not valid". I know your usually supposed to use ==, but I don't know what I am missing here. Thank you for your help.

puts "How are you?"
answer = gets
if (answer == "Good");
    print("Good to hear")
elsif (answer == "Bad");
    print("Oh no")
else;
    print("Not valid")
end
1
  • Are those semicolons ok? Commented Apr 14, 2021 at 18:36

1 Answer 1

1

gets will capture a string including an endline character (\n). You're comparing the string Good (for example) against Good\n, and it obviously doesn't match.

You can observe this by adding a line after you populate answer, like puts answer.inspect (or more tersely, p answer). This will show you the string along with any not-normally-visible characters.

The easiest way to fix this will be to use answer = gets.strip, which will remove whitespace characters (including spaces, tabs, and newlines) from end of the captured input string.

Sign up to request clarification or add additional context in comments.

Comments

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.