相关疑难解决方法(0)

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

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

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
Run Code Online (Sandbox Code Playgroud)

这个代码在do ... while循环中看起来更好看:

people = []

do
    info = gets.chomp
    people += [Person.new(info)] if not info.empty?
while not info.empty?
Run Code Online (Sandbox Code Playgroud)

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

不幸的是,Ruby中似乎不存在这种类型的循环.任何人都可以建议一个更好的方法吗?

ruby loops

448
推荐指数
7
解决办法
25万
查看次数

标签 统计

loops ×1

ruby ×1