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?
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.
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.
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.
...The best I could come up with is the loop
construct with a break
at the end:
loop do
...
break unless condition
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With