【问题标题】:how can I store each instance of the loop?如何存储循环的每个实例?
【发布时间】:2020-08-22 09:04:48
【问题描述】:

我有以下方法可以让用户要求饮料最多 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】:

    您可以通过将用户输入添加到循环外的变量来重复捕获用户输入:

    # 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"]
    

    【讨论】:

    • 当我尝试这个时,它似乎没有将获取值插入到数组中。只需在每个循环上保持一个空数组即可。
    • 您是否在循环外分配了input = []?它很难帮助您编写代码,因为它不是一个可重现的最小示例,并且到处都有很多零碎的东西。
    • 实际上我让它工作了。现在唯一的问题是它保存了每个额外的实例而不是第一个实例(我用不同的方法记录了它)。所以我想我必须玩它并弄清楚如何重新排列它。如果您看到这样做的简单方法,请告诉我。谢谢你的帮助,你太棒了!!!!
    猜你喜欢
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多