我使用这段代码让用户输入名称,而程序将它们存储在一个数组中,直到他们输入一个空字符串(他们必须在每个名称后按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

这段代码在do…while循环:

people = []

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

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

不幸的是,Ruby中似乎不存在这种类型的循环。谁能提出一个更好的方法来做这件事?


当前回答

这个怎么样?

people = []

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

其他回答

这个怎么样?

people = []

until (info = gets.chomp).empty?
  people += [Person.new(info)]
end
a = 1
while true
  puts a
  a += 1
  break if a > 10
end

是这样的:

people = []

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

参考:Ruby的Hidden do {} while()循环

ppl = []
while (input=gets.chomp)
 if !input.empty?
  ppl << input
 else
 p ppl; puts "Goodbye"; break
 end
end

这是另一个:

people = []
1.times do
  info = gets.chomp
  unless info.empty? 
    people += [Person.new(info)]
    redo
  end
end