Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "each"-ing a range only work with incrementing ranges? [duplicate]

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)

like image 598
Blake Avatar asked Mar 13 '26 17:03

Blake


2 Answers

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)

like image 113
Blake Avatar answered Mar 15 '26 07:03

Blake


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

like image 43
Darkmouse Avatar answered Mar 15 '26 06:03

Darkmouse