Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Ruby have a built-in do ... while?

Ruby has a wealth of conditional constructs, including if/unless, while/until etc.

The while block from C:

while (condition) {
    ...
}

can be directly translated to Ruby:

while condition 
    ...
end

However, I can't seem to find a built-in equivalent in Ruby for a C-like do ... while block in which the block contents are executed at least once:

do { 
    ... 
} while (condition);

Any suggestions?

like image 420
Cristian Diaconescu Avatar asked Oct 10 '08 09:10

Cristian Diaconescu


People also ask

Does Ruby have do while loop?

The Ruby do while loop iterates a part of program several times. It is quite similar to a while loop with the only difference that loop will execute at least once. It is due to the fact that in do while loop, condition is written at the end of the code.

How do you use time in Ruby?

The times function in Ruby returns all the numbers from 0 to one less than the number itself. It iterates the given block, passing in increasing values from 0 up to the limit. If no block is given, an Enumerator is returned instead. Parameter: The function takes the integer till which the numbers are returned.

How do you end a while loop in Ruby?

In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.


1 Answers

...The best I could come up with is the loop construct with a break at the end:

loop do
    ...
    break unless condition
end
like image 110
Cristian Diaconescu Avatar answered Sep 27 '22 20:09

Cristian Diaconescu