Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over a reversed range with a specific step in Ruby?

I can iterate like this

(0..10).step(2){|v| puts v}

but, since reversed range is equal to empty range, I cannot iterate this way

(10..0).step(2){|v| puts v}

it will earn me nothing. Of course, I can iterate backward like this

10.downto(0){|v| puts v}

but downto method doesn't allow me to set other step except default 1. It's something very basic, so I suppose there should be a built-in way to do this, which i don't know.

like image 410
user1887348 Avatar asked Mar 30 '13 06:03

user1887348


People also ask

How to loop an array 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 ...

Is there for loop in Ruby?

“for” loop has similar functionality as while loop but with different syntax. for loop is preferred when the number of times loop statements are to be executed is known beforehand. It iterates over a specific range of numbers.

How to exit loop 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.


1 Answers

Why don't you use Numeric#step:

From the docs:

Invokes block with the sequence of numbers starting at num, incremented by step (default 1) on each call. The loop finishes when the value to be passed to the block is greater than limit (if step is positive) or less than limit (if step is negative). If all the arguments are integers, the loop operates using an integer counter. If any of the arguments are floating point numbers, all are converted to floats, and the loop is executed floor(n + n*epsilon)+ 1 times, where n = (limit - num)/step. Otherwise, the loop starts at num, uses either the < or > operator to compare the counter against limit, and increments itself using the + operator.

irb(main):001:0> 10.step(0, -2) { |i| puts i }
10
8
6
4
2
0
like image 99
the Tin Man Avatar answered Oct 26 '22 23:10

the Tin Man