Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write negative loop in ruby like for(i=index; i >= 0; i --)

Tags:

loops

ruby

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; } 
like image 281
Manish Shrivastava Avatar asked Jan 19 '12 13:01

Manish Shrivastava


People also ask

How do you write a for loop in Ruby?

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 ...

How do you end a 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.

How does for loop work in Ruby?

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.

How do you increment in Ruby?

To increment a number, simply write x += 1 .


2 Answers

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 
like image 132
gsoni Avatar answered Oct 11 '22 23:10

gsoni


One way:

25.downto(0) do |i|   puts i end 
like image 42
Mark Thomas Avatar answered Oct 12 '22 00:10

Mark Thomas