Thành Đỗ
Thành Đỗ

Reputation: 11

Why the loop .each in ruby just runs a half?

I got a problem while using this loop:

a = [1,2,3,4]
a.each{puts "#{a.shift}"}

a I just got 1, 2. Any one can help me?

Upvotes: 1

Views: 237

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Array#shift modifies an array inplace. One might either iterate and print values, or use a loop unless the mutated array is empty:

a.each { |elem| puts elem }
#⇒ a is still [1,2,3,4]

or

while a.size > 0 do puts a.shift end
#⇒ a is empty []

or

until a.empty? do puts a.shift end
#⇒ a is empty []

In your example a is mutated, hence on third iteration there is no more elements to iterate.

Upvotes: 1

Will Richardson
Will Richardson

Reputation: 7970

Array#shift removes the first value from an array and returns it. So when you're looping through the array, the array is modified.

The each method seems to basically loop until the index is greater than or equal to the length of the array. Because you're removing elements from the array as you loop the array's length decreases. When you have removed two elements the index is at 2 and the length is 2, so the .each loop exits.

i.e.:

Index: 0
Array: [1, 2, 3, 4]
Print: 1

Index: 1
Array: [2, 3, 4]
Print: 2

Index: 2 # Exit here
Array: [3, 4]

Upvotes: 5

Related Questions