在Ruby中,循环中的返回值是什么?

dev*_*098 4 ruby loops

使用以下代码:

  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循环返回什么值,如果有返回值的话?

fl0*_*00r 5

循环的回报(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作为结果(隐式breakbreak nil),除非你使用显式break "something".如果你想分配循环的结果,你应该使用break这个:x = loop do break 1; end

  • @ programmer321:是的,`break`将a)立即终止循环并且b)使循环计算传递给`break`的值,其方式与`return`将立即终止方法(或lambda)和make方法调用计算传递给`return`的值,`next`将立即终止一个块并使该块计算为传递给`next`的值.主要的区别是如果相应的关键字是*not*使用会发生什么:块,方法和lambdas(以及模块和类定义)计算为最后一个被评估的表达式的值 (2认同)
  • ......而`while`和`until`循环评估为'nil`.一个`for` /`in`迭代器,OTOH,是'each`的一种语法糖,只是简单地计算`each`的返回值(根据标准协议是'self`,但是没有强制执行办法). (2认同)