是否有“做...而"?在 Ruby 中循环? [英] Is there a "do ... while" loop in Ruby?

查看:19
本文介绍了是否有“做...而"?在 Ruby 中循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using this code to let the user enter in names while the program stores them in an array until they enter an empty string (they must press enter after each name):

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 循环中看起来会更好:

This code would look much nicer in a do ... while loop:

people = []

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

在这段代码中,我不必将信息分配给某个随机字符串.

In this code I don't have to assign info to some random string.

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

Unfortunately this type of loop doesn't seem to exist in Ruby. Can anybody suggest a better way of doing this?

推荐答案

注意:

开始end while 被 Ruby 的作者 Matz 拒绝了.相反,他建议使用 Kernel#loop,例如

The begin <code> end while <condition> is rejected by Ruby's author Matz. Instead he suggests using Kernel#loop, e.g.

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

这是电子邮件交流2005 年 11 月 23 日,Matz 指出:

Here's an email exchange in 23 Nov 2005 where Matz states:

|> 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 也有类似的故事:

在 2005 年 11 月,Ruby 的创造者 Yukihiro Matsumoto 对这个循环特性感到遗憾,并建议使用 Kernel#loop.

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

这篇关于是否有“做...而"?在 Ruby 中循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆