使用以下代码:
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
循环返回什么值,如果有返回值的话?
答案 0 :(得分:5)
循环(loop
,while
,until
等)的返回可以是您发送给break
的任何内容
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
或者您可以使用begin .. while
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
,break nil
),除非您使用显式break "something"
。如果要分配循环结果,则应使用break
:x = loop do break 1; end
答案 1 :(得分:0)
loop
也可以在不使用break
def loop_return
@a = [1, 2, 3 ].to_enum
loop do
@a.next
end
end
print loop_return #=> [1, 2, 3]