使用以下代码:
  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循环是否返回什么值?
发布于 2016-11-11 22:34:03
循环(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
endPS:循环本身返回零作为结果(隐式break,即break nil),除非使用显式break "something"。如果您想要分配循环的结果,则应该使用break进行以下操作:x = loop do break 1; end
发布于 2018-04-07 05:01:22
loop也可以不使用break返回值。
def loop_return
  @a = [1, 2, 3 ].to_enum
  loop do
    @a.next
  end
end
print loop_return  #=> [1, 2, 3]https://stackoverflow.com/questions/40557171
复制相似问题