Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

loops

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?

like image 936
Paige Ruten Avatar asked Sep 25 '08 23:09

Paige Ruten


People also ask

What is do in Ruby?

The do keyword comes into play when defining an argument for a multi-line Ruby block. Ruby blocks are anonymous functions that are enclosed in a do-end statement or curly braces {} . Usually, they are enclosed in a do-end statement if the block spans through multiple lines and {} if it's a single line block.

What is while loop in Ruby?

Ruby while StatementExecutes code while conditional is true. A while loop's conditional is separated from code by the reserved word do, a newline, backslash \, or a semicolon ;.

Which of the following is not a looping statement in Ruby?

Which of the following is not a type of loop in ruby? Explanation: Foreach loop is not there in ruby.


1 Answers

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.

like image 56
Siwei Avatar answered Sep 19 '22 14:09

Siwei