Search code examples
rubychomp

Code never enter any of the if statements


begin
  selected_option = gets.chomp
  if selected_option == 1
    puts "Welcome to the Welcome Screen!"
  elsif selected_option == 2
    puts "This is the options menu."
  elsif selected_option == 3
    puts "Logging out. Goodbye!"
  else
    puts "Please select a valid option."
  end  
end while not selected_option == 3

I enter in 1 or 2 or 3 and I always get the "Please enter a valid option" message. I'm guessing that's because the chomp method retrieves the input as a string.

Any way around this sans using quotes around the options?


Solution

  • gets.chomp.to_i
    

    Will convert it to an integer.

    You may also want to use a switch instead:

    begin
      selected_option = gets.chomp.to_i
      case selected_option
        when 1
          puts "Welcome to the Welcome Screen!"
        when 2
          puts "This is the options menu."
        when 3
          puts "Logging out. Goodbye!"
        else
          puts "Please select a valid option."
      end  
    end while not selected_option == 3