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.
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 ...
“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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With