2017-03-14 13 views
1

ユーザタイプがdoneでループを中断しようとしています。残った質問をいくつか質問する「調査」という別の方法にジャンプします。ユーザが特定の入力を入力したときにループを壊す

これは私が今持っているものである:それはちょうど私が1つのアレルギーを入力することができますし、thenk右の調査方法にスキップ現時点で

def survey 
    puts "For how many years have you had these allergies?" 
    name = gets.chomp.to_i 

    puts "When was your last allergy reaction?" 
    reaction = gets.chomp.to_i 
end 

def allergies 

    puts "Please enter all your allergies. When you are finished, type 'done'." 
    allergy = gets.chomp.downcase! 

    while allergy != "done" 

     # Format the loop so that when the user types 'done' 
     # The loop breaks and we go to the 'survey' method 

     allergy = gets.chomp.downcase 
     survey 
     if allergy == "nuts" 
      puts "Beware! The food item contains peanuts!" 
      break 
     end 
    end 
end 

allergies 

を。どのように私はこれを変更することができますので、 "ナッツ"または "完了"のいずれかを入力するまで、私はアレルギーを入力し続けることができますか?

+0

if-else文を試してみてください。http://stackoverflow.com/a/42403470/6163262 – whodini9

答えて

2
def survey 
    puts "For how many years have you had these allergies?" 
    name = gets.chomp.to_i 

    puts "When was your last allergy reaction?" 
    reaction = gets.chomp.to_i 
end 

def allergies 

    puts "Please enter all your allergies. When you are finished, type 'done'." 
    allergy = gets.chomp.downcase! 

    while allergy != "done" 

     # Format the loop so that when the user types 'done' 
     # The loop breaks and we go to the 'survey' method 

     allergy = gets.chomp.downcase 
     if allergy == "nuts" 
      puts "Beware! The food item contains peanuts!" 
      break 
     elsif allergy == "done" 
      survey 
     end 
    end 
end 

allergies 
+0

感謝を!それはそれを解決しました:+1: – CarlosG90

2

これはまさにここで回答され

def allergies 

    puts "Please enter all your allergies. When you are finished, type 'done'." 
    allergy = gets.chomp.downcase! 

    while allergy != "done" 
     if allergy == "nuts" 
      puts "Beware! The food item contains peanuts!" 
      break 
     else 
      survey 
     end 

     allergy = gets.chomp.downcase 
    end 
end 
関連する問題