Decrementing loop:
Let’s start with a siimple decrementing loop in ruby:
This produces all integers from 100 to 1, each on a separate line:
To produce a slightly more legible output that does not crown our terminal, use print
instead of puts
Output:
There is also a downto
method:
My favorite – that I always conveniently forget about on the spot – is reverse_each
reverse_each
is really a play on the regular each
method used with a range, with would iterate through a loop in ascending order:
To go a little bit fancier and with needless amount of work really, populate and array from a range and then iterate over it:
Let’s not forget the step
method:
Decrementing | incrementing loop:
What if the task is to have the x
counting down, but to have the integers in the output counting up?
There is a very simple mathematical solution to the problem:
The result is exactly what we are looking for:
(Here I also added a newline so that it does not clash with terminal prompt.)
I thought of this when asked on the spot, but it’s not exactly an elegant solution:
Incrementing counter | decrementing output:
Easy and more or less creative solution using a previously populated array for a counter that goes up from 1 to 100 and for an output that goes down from 100 to 1:
Output: