gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:16:10 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com