How can I write a loop in Ruby that counts down, similar to the following C-style for
loop?
for (i = 25; i >= 0; i--) { print i; }
The simplest way to create a loop in Ruby is using the loop method. loop takes a block, which is denoted by { ... } or do ... end . A loop will execute any code within the block (again, that's just between the {} or do ...
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.
Ruby until loop will executes the statements or code till the given condition evaluates to true. Basically it's just opposite to the while loop which executes until the given condition evaluates to false. An until statement's conditional is separated from code by the reserved word do, a newline, or a semicolon.
To increment a number, simply write x += 1 .
There are many ways to perform a decrementing loop in Ruby:
First way:
for i in (10).downto(0) puts i end
Second way:
(10).downto(0) do |i| puts i end
Third way:
i=10; until i<0 puts i i-=1 end
One way:
25.downto(0) do |i| puts i 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