user5208585
user5208585

Reputation:

elsif not working, continues putting if input

In my code, elsif does not work. If I type "N" or "n", it will ask me for the password rather than puts, which it is supposed to do:

puts "Would you like to access Your Software Wizard?"
puts "Type Y for Yes and N for No"
answer = gets.to_s
y = "yes"
n = "no"
Y = "yes"
N = "no"
if answer == y or Y
  puts " Please Insert Password:"
  password = gets.to_s
elsif answer == n or N
  puts "Quitting..... an Alert Email and an Alert Sms has been sent to  User of attempted access"
  puts "Password has been changed and newly encripted"
  puts "Good Bye"
end

What am I doing wrong?

Upvotes: 1

Views: 50

Answers (2)

the Tin Man
the Tin Man

Reputation: 160631

You have several problems in your code but you've run into one of the most common, a misunderstanding of how gets works:

  1. answer=gets.to_s doesn't return what you think it does. Consider this IRB session where I entered 1Return:

    >> gets
    1
    "1\n"
    

    gets is returning a string terminated with the "\n" which was input when Return or Enter was pressed.

  2. Using to_s doesn't help, because gets is already returning a String. Like the above example, I entered 1:

    >> gets.class
    1
    String < Object
    
  3. Comparing the output of gets has to allow for the trailing "\n" somehow:

    >> gets.strip
    1
    "1"
    >> gets.chomp
    1
    "1"
    >> gets == "1\n"
    1
    true
    >> gets.chomp == '1'
    1
    true
    

Knowing all that, meditate on this:

>> answer = gets.chomp.downcase
YES
"yes"
>> answer == 'yes'
true

You have logic errors also, because you can't use if answer == y or Y or answer == n or N, but that's covered in https://stackoverflow.com/a/31971730/128421.

Upvotes: 0

Philip Hallstrom
Philip Hallstrom

Reputation: 19899

Change if answer == y or Y to if answer == y || answer == Y or if [y, Y].include?(answer) (and similarly for the elsif condition).

answer == y or Y is testing is answer equal to the value of y OR is the value of Y true. The value of Y will always be true as you've set it to a valid string.

Upvotes: 4

Related Questions