Как заставить мою текущую программу ruby ​​перебирать три параметра ввода и отображать, использовался ли один и тот же параметр дважды?

Я пытаюсь заставить мою текущую программу предоставить пользователю три разных параметра ввода и уведомить пользователя, если он пытался использовать один и тот же параметр ввода дважды. Мой текущий код:

prompt = "Do you want to use the Subscription coupon[1] the one-time pay-per-use 
coupon[2] or the gift purchase coupon[3]: "
print prompt
code = gets.chomp
code = code.to_i
history = []

loop do
    if code == 1
            puts "Subscription coupon used"
            print prompt
            code = gets.chomp
    elsif code == 2
            puts "One-time pay-per-use coupon used"
            print prompt
            code = gets.chomp
    elsif code == 3
            puts "Gift purchase coupon used"
            print prompt
            code = gets.chomp
    else history.include? code
            puts "Code already input"
            print prompt
            code = gets.chomp
    end
end

Это позволяет мне вводить столько раз, сколько я хочу, но независимо от того, какой второй ввод, он печатает код уже введенного текста.

Как исправить код, чтобы он работал по назначению?

🤔 А знаете ли вы, что...
Один из наиболее известных гемов - Devise, который предоставляет готовое решение для аутентификации и управления пользователями.


50
2

Ответы:

Решено

Переместите проверку истории в начало цикла и фактически заполните историю. Вот один из многих способов добиться этого:


loop do
  if history.include?(code)
    puts 'Code already input'
    print prompt
    code = gets.chomp.to_i
    next # Stop processing this iteration of the loop immediately, and skip to the next iteration.
  else
    history << code
  end

  if code == 1
    puts 'Subscription coupon used'
  elsif code == 2
    puts 'One-time pay-per-use coupon used'
  elsif code == 3
    puts 'Gift purchase coupon used'
  else
    puts 'Invalid entry.'  
  end

  print prompt
  code = gets.chomp.to_i
end

Вы можете написать это следующим образом. Обратите внимание, что я немного добавил.

valid_entries = ["1", "2", "3", "4"]
answers = []

loop do
  puts  "\nDo you want to use the"
  puts  "  Subscription coupon (1)"
  puts  "  One-time pay-per-use coupon (2) or"
  puts  "  Gift purchase coupon (3)?"
  puts  "Enter (4) if you are finished"
  print "Your selection: "

  entry = gets.chomp

  unless valid_entries.include?(entry)
    puts "'#{entry}'is not a valid entry, you dummy. Try again."
    next
  end

  if answers.include?(entry)
    puts "You've already made that selection. Try again."
    next
  else
    answers << entry
  end

  break if entry == "4"

  puts case(entry)
    when '1' then "Subscription coupon used"
    when '2' then "One-time pay-per-use coupon used"
    when '3' then "Gift purchase coupon used"
  end
end

Вот возможный разговор.

Do you want to use the
  Subscription coupon (1)
  One-time pay-per-use coupon (2) or
  Gift purchase coupon (3)?
Enter (4) if you are finished
Your selection: 1
Subscription coupon used
Do you want to use the
  Subscription coupon (1)
  One-time pay-per-use coupon (2) or
  Gift purchase coupon (3)?
Enter (4) if you are finished
Your selection: 2
One-time pay-per-use coupon used
Do you want to use the
  Subscription coupon (1)
  One-time pay-per-use coupon (2) or
  Gift purchase coupon (3)?
Enter (4) if you are finished
Your selection: 1
You've already made that selection. Try again.
Do you want to use the
  Subscription coupon (1)
  One-time pay-per-use coupon (2) or
  Gift purchase coupon (3)?
Enter (4) if you are finished
Your selection: %
'%'is not a valid entry, you dummy. Try again.
Do you want to use the
  Subscription coupon (1)
  One-time pay-per-use coupon (2) or
  Gift purchase coupon (3)?
Enter (4) if you are finished
Your selection: 4

В качестве альтернативы

puts case(entry)
  when '1' then "Subscription coupon used"
  when '2' then "One-time pay-per-use coupon used"
  when '3' then "Gift purchase coupon used"
end

ты мог бы написать

puts MESSAGES[entry]

после определения константы

MESSAGES = { '1'=>"Subscription coupon used",
             '2'=>"One-time pay-per-use coupon used"
             '3'=>"Gift purchase coupon used" }