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

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


There are many ways to perform a decrementing loop in Ruby:

First way:

for i in (10).downto(0)  puts iend

Second way:

(10).downto(0) do |i|  puts iend

Third way:

i=10;until i<0  puts i  i-=1end


One way:

25.downto(0) do |i|  puts iend


downto is fine, but there is also the more generic step.

25.step(0, -1){|i| puts i}