Why will a Range not work when descending?

larryzhao picture larryzhao · Jan 11, 2012 · Viewed 11.1k times · Source

Why will (1..5).each iterate over 1,2,3,4,5, but (5..1) will not? It returns the Range instead.

1.9.2p290 :007 > (1..5).each do |i| puts i end
1
2
3
4
5
 => 1..5
1.9.2p290 :008 > (5..1).each do |i| puts i end
 => 5..1

Answer

Derek Organ picture Derek Organ · Jan 11, 2012

The easiest way to do that is use downto

5.downto(1) do |i| puts i end