【问题标题】:validation on user input ruby验证用户输入 ruby
【发布时间】:2020-07-23 00:08:05
【问题描述】:

我创建了一个 gem,它通过用户输入来查找食谱。我有近 1000 个食谱可供搜索。当用户输入与我的食谱名称不匹配时,如何验证用户输入?

例如,当用户键入 nabucodonosor 或 vocka 时,方法 load_recipe_by_ingridients 返回空,我希望我能解决这个问题。我正在使用 Ruby vanilla.. 没有轨道

def start
  puts "Hey there! you hungry? lets find some recipes ideas for you."
        
  list_recipe_by_ingredients
  show_summary
    
  while @input != "exit" 
    if @input == "back"
      list_recipe_by_ingredients
    elsif valid_input?
      puts Recipe.find_by_number(@input).summary
    else
      puts "Ops! not a valid number. try again."
    end

    ask_for_choices
  end
end

def load_recipe_by_ingredients
  puts "Search for recipes with the main ingredient, example: milk, pizza, eggs flour, ect."
  @input = gets.strip.downcase
  puts " "
  Recipe.search_for_recipes(@input).each.with_index(1) do |recipe, index|
    puts "#{index}. #{recipe.title}"
  end
end
   

【问题讨论】:

  • 您希望它做什么?验证是什么意思?有效输入会是什么样子?无效输入会是什么样子?
  • 嗨,我正在通过用户输入搜索食谱,但是当我的食谱对象中不存在该输入时,我想告诉用户再试一次。有效的输入将是面包、比萨饼、鸡蛋或任何与食物相关的东西。当我放一些与食物无关的东西时,我的列表方法返回空。
  • 好吧,你怎么打电话给load_recipe_by_ingredients?有某种循环吗?请出示该代码。
  • 代码在问题上。

标签: ruby input command-line-interface


【解决方案1】:

一个非常简单的解决方案是 loop 直到找到一个配方,一旦找到一个或多个配方,你就可以 break 退出循环然后渲染它们:

def load_recipe_by_ingredients
  recipes = []

  loop do
    puts 'Search for recipes with the main ingredient, example: milk, pizza, eggs flour, etc.'
    input = gets.strip.downcase
    puts
    recipes = Recipe.search_for_recipes(input)
    break if recipes.any?
    puts 'No recipes found, please try again'
  end

  recipes.each.with_index(1) do |recipe, index|
    puts "#{index}. #{recipe.title}"
  end
end

【讨论】:

    猜你喜欢
    • 2018-06-28
    • 2015-07-13
    • 2017-09-11
    • 1970-01-01
    相关资源
    最近更新 更多