使用以下代码:
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
Run Code Online (Sandbox Code Playgroud)
以下代码获取用户响应,并最终将其操作返回到另一个方法.
我知道一个循环会重复,直到它最终被破坏,但对返回值很好奇,所以我可以更好地构建下一次的循环.在until循环中,我很想知道until循环返回什么值,如果有返回值的话?
循环的回报(loop,while,until等),可以是任何你发送给break
def get_action
loop do
action = gets.chomp
break action if Guide::Config.actions.include?(action)
end
end
Run Code Online (Sandbox Code Playgroud)
要么
def get_action
while action = gets.chomp
break action if Guide::Config.actions.include?(action)
end
end
Run Code Online (Sandbox Code Playgroud)
或者你可以使用 begin .. while
def get_action
begin
action = gets.chomp
end while Guide::Config.actions.include?(action)
action
end
Run Code Online (Sandbox Code Playgroud)
甚至更短
def get_action
action = gets.chomp while Guide::Config.actions.include?(action)
action
end
Run Code Online (Sandbox Code Playgroud)
PS:循环本身返回nil作为结果(隐式break的break nil),除非你使用显式break "something".如果你想分配循环的结果,你应该使用break这个:x = loop do break 1; end