Q:

Why doesn't 'each' iterator go through the whole array?

I tried to execute this code in Ruby:
array=[1,2,3,4,5]
array.each do |x|
  puts array.length
  puts "Downloading #{array.length} files"
  array.pop
end

I got:
5
Downloading 5 files
4
Downloading 4 files
3
Downloading 3 files

I don't understand why I'm getting only three iterations. What am I doing wrong (apart from not using a while loop)?

A:

What happened before was this:

array.length is 5
x = 1 is being processed
array.shift (array.length is 4)
Array length = 4
x = 2 is being processed
array.shift (array.length is 3)
x = 3 is being processed
array.shift (array.length is 2)

Now there are no more array items to iterate through, because the last 3 items (3,4,5) are popped.
A better way to do is to reverse the array and shift it
array=[1,2,3,4,5]

array.reverse.each do |x|
  puts array.length
  puts "Downloading #{array.length} files"
  array.shift
end

What happens now is, the array now is [5,4,3,2,1].
Each loop it processes the first item in the array, puts the array length, and then removes the value using shift.

