0

我正在尝试通过使用 while 循环从用户那里获取有效输入。因此,如果输入无效,我希望每次用户未提供有效输入时都会出现错误消息并重复出现

这是我的代码 -

def suburb
#user prompt to get information for URL
  puts ' Hey there welcome to house_search! Please which suburb you would like to search...'
  puts '1. sub1 2. sub2'
    suburb_input = input
    while suburb_input != "1" or "2"
        p "please try again"
        suburb_input
    end
end

有谁知道做到这一点的最佳方法?

4

1 回答 1

1

您想放置gets在 while 语句中,以便它不断获取用户输入,直到您退出循环。

def suburb
  puts 'Hey there welcome to house_search! Please choose which suburb you would like to search...'
  puts '1. sub1 2. sub2'
  while input = gets.chomp
    if input == '1' || input == '2'
      puts "Jolly good!"
      break # exits the loop
    else 
      puts "please try again" # the loop continues
    end 
  end
end

小心使用orandand运算符。它们的优先级低于||&&

于 2020-04-06T11:01:12.487 回答