Why does this code delete only even elements within the array? I would expect the for loop to iterate through each value, 0 through 3, and delete each element one at a time. But it is only deleting a[0] and a[2]. What am I doing wrong? Thanks in advance–
a=%w(ant bat cat dog)
puts a.inspect #output: ["ant", "bat", "cat", "dog"]
for k in (0..3)
a.delete_at(k)
end
puts a.inspect #output: ["bat", "dog"]
UPDATE–
Thank you for your responses; I see what I was doing now. In order to delete each element of the array, the Array method ‘shift’ would be appropriate. For example:
for each in (0..3)
a.shift
print a
end
This would shift the first element out of the array, and move each subsequent element forward one cell. Thank you for the recommendation to use ‘each’–I can see that it is the preferred syntax.
UPDATE 2–
Would the following section of code be more representative of proper ruby syntax?
(0..3).to_a.each do
a.shift
p a
end
And Thanks to Glenn for the suggestions on deleting contents of an array.
Because when you delete element 0 element 1 would be element 2 of the original array.