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;
}
One way:
25.downto(0) do |i|
puts i
end
Try this:
25.downto(0) { |i| puts i }
Print reverse array elements:
nummarray = [3,4,7,3,6,8]
(numarray.length-1).downto(0){ |i| print numarray[i] }
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
downto
is fine, but there is also the more generic step
.
25.step(0, -1){|i| puts i}
Just in case you are working with a range already:
rng = 0..6
rng.reverse_each { |i| p i }
EDIT - more succinctly:
puts(rng.to_a.reverse)