ruby - Ruby 中有 "do ... while"循环吗?

标签 ruby loops

我使用此代码让用户输入名称,同时程序将它们存储在数组中,直到他们输入一个空字符串(他们必须在每个名称后按回车键):

people = []
info = 'a' # must fill variable with something, otherwise loop won't execute

while not info.empty?
    info = gets.chomp
    people += [Person.new(info)] if not info.empty?
end

这段代码在 do ... while 循环中看起来会好得多:

people = []

do
    info = gets.chomp
    people += [Person.new(info)] if not info.empty?
while not info.empty?

在这段代码中,我不必将信息分配给一些随机字符串。

不幸的是,Ruby 中似乎不存在这种类型的循环。有人可以建议更好的方法吗?

最佳答案

注意:

begin <code> end while <condition>被 Ruby 的作者 Matz 拒绝了。相反,他建议使用 Kernel#loop ,例如

loop do 
  # some code here
  break if <condition>
end 

这是 an email exchange 2005 年 11 月 23 日,Matz 指出:

|> Don't use it please.  I'm regretting this feature, and I'd like to
|> remove it in the future if it's possible.
|
|I'm surprised.  What do you regret about it?

Because it's hard for users to tell

  begin <code> end while <cond>

works differently from

  <code> while <cond>

RosettaCode wiki有一个类似的故事:

During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop.

关于ruby - Ruby 中有 "do ... while"循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/136793/

相关文章:

ruby - 如何使用 Discordrb Api 共享图像?

ruby - Sinatra SASS 自定义目录

ruby-on-rails - 传递给 Controller ​​的模型 Rub​​y Rails 验证失败

java - 获取出现次数最大次数

arrays - 如何遍历字典数组?

java - 单独的字符串输入

ruby - 带有 mongolab 镜像和后备的本地 mongo 服务器

ruby-on-rails - rake 如何修复未定义的局部变量或方法错误?

php - 如何在循环中设置html布局

java - 为什么我的字符串索引超出范围?