Как дать альтернативный запрос, если ввод неоднократно неверен - PullRequest
0 голосов
/ 07 ноября 2019

Я хочу, чтобы моя программа печатала альтернативную строку, если введенные пользователем данные неверны пять раз. Код, который я использую ниже, дает мне undefined method `+' for nil:NilClass (NoMethodError) со ссылкой на +=, и я не уверен, почему.

loop do
  input = gets.chomp
  if input =~ /\d/
    #long case statement here
  else
    annoyed += 0
    if annoyed == 5 
      puts "alternate prompt"
    else
      puts "normal prompt"
    end
  end
end

1 Ответ

1 голос
/ 07 ноября 2019

@ radubogdan в комментарии объяснил проблему с вашим кодом. Попробуйте написать что-то вроде следующего.

wrong_answers = 0

loop do
  print wrong_answers < 5 ?
    "Will you agree to tell me who your handler is?: " :
    "Your life is toast if you don't tell me. Will you tell me now?: "
  if gets.chomp.match?(/yes/i)
    puts "You've come to your senses"
    puts "executing code..."
    break
  end
  puts "You're lying"
  wrong_answers += 1
end

Может произойти следующий разговор.

Will you agree to tell me who your handler is?: no 
You're lying
Will you agree to tell me who your handler is?: No!
You're lying
Will you agree to tell me who your handler is?: nyet
You're lying
Will you agree to tell me who your handler is?: shove it
You're lying
Will you agree to tell me who your handler is?: never!
You're lying
Your life is toast if you don't tell me. Will you tell me now?: don't hit me again
You're lying
Your life is toast if you don't tell me. Will you tell me now?: #%$ **#
You're lying
Your life is toast if you don't tell me. Will you tell me now?: yes
You've come to your senses
executing code...

Я написал print arg где:

arg = wrong_answers < 5 ? "Will you agree..." : "Your life is toast..."

В правой части этого выражения используется троичный оператор .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...