我如何存储循环的每个实例?

问题描述 投票:1回答:1

我有以下方法,允许用户最多喝6次酒。每次他们选择饮料时,它可能是新饮料,或菜单列表中的相同饮料。如何记录每个循环中的用户响应?

def display
  menu_list = AlcoholicBeverage.pluck(:cocktail_name)
  puts menu_list
  sleep(0.1)
  puts "So, what's your poison?" "\n" 
end

def drink_valid?
  chosen_cocktail = gets.chomp.titleize
  until AlcoholicBeverage.find_by(cocktail_name: chosen_cocktail)
    puts "Sorry please choose something on the list!"
    chosen_cocktail = gets.chomp.titleize
  end

  puts "Mmmm good choice!"
  puts "Now that you've chosen your cocktail, I'll provide you with details on the necessary ingredients,glass and garnishes!"

  glass_type = AlcoholicBeverage.where(cocktail_name: chosen_cocktail).map(&:glass)
  puts "Required : #{glass_type.join.titleize} glass."

  garnish = AlcoholicBeverage.where(cocktail_name: chosen_cocktail).map(&:garnish)
  if garnish.join.titleize == ""
    puts "No garnish needed!"
  else
    puts "Required garnish: #{garnish.join.titleize}"
  end

  preparation = AlcoholicBeverage.where(cocktail_name: chosen_cocktail).pluck("preparation")
  puts "To prepare : #{preparation.join}"
end

def ask
  counter=0
  while counter < 6
    puts "Would you like another drink (yes/no)?"
    new_drink = gets.chomp.strip.titleize

    if new_drink == "Yes" || new_drink == "yes"
      display
      drink_valid?
    else
      puts "I'll give your blood alcohol content level based on the drinks you've had."
    end
    counter +=1
  end
end
ruby activerecord while-loop iteration
1个回答
0
投票

您可以通过将用户输入从循环外部添加到变量中来反复捕获用户输入:

# main.rb
inputs = []
until inputs.size >= 6
  puts "Please input a value or leave blank to exit"
  input = gets.chomp
  break if input == ""
  inputs << input
end

puts "You have input the following: #{inputs.inspect}"
$ ruby main.rb
Please input a value or leave blank to exit
1
Please input a value or leave blank to exit
2
Please input a value or leave blank to exit
3
Please input a value or leave blank to exit
4
Please input a value or leave blank to exit
5
Please input a value or leave blank to exit
6
You have input the following: ["1", "2", "3", "4", "5", "6"]
$ ruby main.rb
Please input a value or leave blank to exit
1
Please input a value or leave blank to exit
2
Please input a value or leave blank to exit

You have input the following: ["1", "2"]
© www.soinside.com 2019 - 2024. All rights reserved.