(1..10).each do |x| irb(main):002:1* puts...">

Why does "each" range only work with increasing ranges?

It doesn't make any 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

      

then:

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 of offering a range iterator and supporting a decrementing range if you can't mix and match the two? Is this something fixed in new versions of ruby? (windows launch)

+3


source to share


2 answers


It turns out that decrementing ranges are not supported. Indeed 10..1

has a range of classes, but iterating over it produces no results (consider (10..1).to_a

an empty list)



+2


source


Ranges in Ruby are only used to increment 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. You could do



10.downto(1).to_a

      

In Ruby, ranges use the <=> operator to indicate the end of an iteration;

5 <=> 1 == 1
5 is greater than 1

      

The next value will be 4, which is not more than 5, but less.

Update: added description

+1


source







All Articles