1

我创建了一个 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
   
4

1 回答 1

0

一个非常简单的解决方案是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
于 2020-07-23T01:27:40.980 回答