Ruby – “do … while” loop in Ruby

loopsruby

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

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.

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

Best Answer

CAUTION:

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 

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 has a similar story:

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