I am attempting to get my current program to give the user three different input options and notify the user if they have attempted to use the same input option twice. My current code:
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
It is allowing me to input as many times as I want, but no matter what the second input is it prints the code already input text.
How do I fix the code to get it to run in the intended way?
CodePudding user response:
Move the history check to the beginning of your loop, and actually populate the history. Here's one of many ways to accomplish that:
loop do
if history.include?(code)
puts 'Code already input'
print prompt
code = gets.chomp
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'
else code == 3
puts 'Gift purchase coupon used'
end
print prompt
code = gets.chomp
end