0
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?

4

1 回答 1

3
gets.chomp.to_i

将其转换为整数。

您可能还想使用开关:

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
于 2011-03-07T01:51:30.750 回答