UPDATE 2: For posterity, this is how I've settled on doing it (thanks to Jorg's input):
100.step(2, -2) do |x|
# my code
end
(Obviously there are plenty of ways to do this; but it sounds like this is the most "Ruby" way to do it; and that's exactly what I was after.)
UPDATE: OK, so what I was looking for was step
:
(2..100).step(2) do |x|
# my code
end
But it turns out that I wasn't 100% forthcoming in my original question. I actually want to iterate over this range backwards. To my surprise, a negative step isn't legal.
(100..2).step(-2) do |x|
# ArgumentError: step can't be negative
end
So: how do I do this backwards?
I am completely new to Ruby, so be gentle.
Say I want to iterate over the range of even numbers from 2 to 100; how would I do that?
Obviously I could do:
(2..100).each do |x|
if x % 2 == 0
# my code
end
end
But, obviously (again), that would be pretty stupid.
I know I could do something like:
i = 2
while i <= 100
# my code
i += 2
end
I believe I could also write my own custom class that provides its own each
method (?). I am almost sure that would be overkill, though.
I'm interested in two things:
(x..y).each
)?Ranges as Sequences Two operators are used for creating ranges, one is Double Dot (..) operator and the another one is Triple Dot (…) operator.
Ruby | Array class first() function first() is a Array class method which returns the first element of the array or the first 'n' elements from the array.
Getting Started with Ranges We use the double dot (..) and triple dot (…) to create a range in Ruby. The double dot notation produces a range of values, including the start and end values of the range. On the other hand, the three-dot notation will exclude the end (high) value from the list of values.
Stepping is the process of controlling step-by-step execution of the program.
You can't declare a Range
with a "step". Ranges don't have steps, they simply have a beginning and an end.
You can certainly iterate over a Range
in steps, for example like this:
(2..100).step(2).reverse_each(&method(:p))
But if all you want is to iterate, then what do you need the Range
for in the first place? Why not just iterate?
100.step(2, -2, &method(:p))
This has the added benefit that unlike reverse_each
it does not need to generate an intermediate array.
This question answers yours: about ruby range?
(2..100).step(2) do |x|
# your code
end
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