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

使用以下代码

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;结束

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...