在Ruby中,循环中的返回值是什么?
发布时间:2020-12-17 02:56:48 所属栏目:百科 来源:网络整理
导读:使用以下代码: 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 以
使用以下代码:
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;结束 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |