使用以下代码:
def get_action action = nil until Guide::Config.actions.include?(action) puts "Actions: " + Guide::Config.actions.join(",") print "> " user_response = gets.chomp action = user_response.downcase.strip end return action end
我知道一个循环会重复,直到它最终被破坏,但对返回值很好奇,所以我可以更好地构建下一次的循环.在until循环中,我很想知道如果有一个返回值,until循环返回的值是多少?
解决方法
循环的返回(循环,while,until等)可以是您发送的任何内容
def get_action loop do action = gets.chomp break action if Guide::Config.actions.include?(action) end end
要么
def get_action while action = gets.chomp break action if Guide::Config.actions.include?(action) end end
或者你可以使用开始…而
def get_action begin action = gets.chomp end while Guide::Config.actions.include?(action) action end
甚至更短
def get_action action = gets.chomp while Guide::Config.actions.include?(action) action end
PS:循环本身返回nil作为结果(隐式中断,它是break nil),除非你使用显式break“something”.如果你想分配循环的结果你应该使用break:x = loop do break 1;结束