This makes absolutely no sense:
irb(main):001:0> (1..10).each do |x|
irb(main):002:1* puts x
irb(main):003:1> end
1
2
3
4
5
6
7
8
9
10
=> 1..10
whereas:
irb(main):004:0> (10..1).each do |x|
irb(main):005:1* puts x
irb(main):006:1> end
=> 10..1
What's the point in offering a range iterator and support for decrementing ranges if you can't mix and match the two? Is this something fixed in newer versions of ruby? (running windows)
It turns out that decrementing ranges are not supported. Indeed 10..1 is of class range, but iterating over it produces no results (consider (10..1).to_a, an empty list)
Ranges in Ruby only use for incrementing values. This can be used for numbers
(1..5).to_a
[1,2,3,4,5]
or even letters
('a'..'e').to_a
['a','b','c','d','e']
There are other options you could try though. You could do
10.downto(1).to_a
In Ruby, ranges use the <=> operator to determine if an iteration is over;
5 <=> 1 == 1
5 is greater than 1
The next value would be 4 which is not greater than 5 but rather less then.
Update: Added explanation
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