Newbie question about if statement

This code doesn’t function the way I expect. The if part is always
skipped no matter what input put into it.

while true
puts “Welcome!”
puts “Please enter ‘the password.’”
x = gets
if x != “the password”
puts “Try again”
next
end
puts “That is correct. Now, please enter your name.”
break
end

I get the same problem if I put

if x == “the password”
puts “correct”
else
puts “try again”
next
end

It doesn’t output “correct” it just skips to the “Try again” and
executes the “next.”

thanks.

After you use “gets”, add this line:

p x

That will allow you see exactly what the variable x contains. You’ll
find that it has a newline character on the end of the string, so
instead of “the password”, it will be “the password\n”

If you want to remove any trailing spaces, and the character you get
from pressing Enter, use gets.chomp

That is a classical newcomer mistake.

Collin, always make sure that your expectation matches the code.

In this context a simple .chomp would remove the trailing newline.

Your variable contains “the password\n”, which is not equal to “the
password”.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs