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

查看:32
本文介绍了是否有一个“做...而..."在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?

推荐答案

注意:

begin <code> end while <condition>被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 

这里是电子邮件交换 Matz在2005年11月23日指出:

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天全站免登陆