until Loops
Ruby also has an until
loop, which can be thought of as a while not loop. Its syntax and options are the same as those applying to while
—that is, the test condition and the code to be executed can be placed on a single line (in which case the do
keyword is obligatory) or can be placed on separate lines (in which case do
is optional). There is also an until
modifier that lets you put the code before the test condition and an option to enclose the code between begin
and end
in order to ensure that the code block is run at least once.
Here are some simple examples of until
loops:
until.rb
i = 10 until i == 10 do puts(i) end # never executes until i == 10 # never executes puts(i) i += 1 end puts(i) until i == 10 # never executes begin # executes ...
Get The Book of Ruby now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.