Wednesday, 22 June 2016

Is there a "do ... while" loop in Ruby?



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?


Answer



CAUTION:



The begin end while is rejected by Ruby's author Matz. Instead he suggests using Kernel#loop, e.g.



loop do 
# some code here
break if
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 end while

works differently from

while


RosettaCode wiki has a similar story:





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



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...