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

时间:2016-11-11 22:24:07

标签: 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

以下代码获取用户响应,并最终将其操作返回给另一个方法。

我知道一个循环会重复,直到它最终被破坏,但对返回值很好奇,所以我可以更好地构建下一次的循环。在until循环中,我很想知道until循环返回什么值,如果有返回值的话?

2 个答案:

答案 0 :(得分:5)

循环(loopwhileuntil等)的返回可以是您发送给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作为结果(隐式breakbreak nil),除非您使用显式break "something"。如果要分配循环结果,则应使用breakx = 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]