Reputation: 7
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
Upvotes: 0
Views: 29
Reputation: 62688
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.
Upvotes: 1