Why does this code only remove even-numbered elements in the array? I would expect the for loop to go through each value, from 0 to 3, and delete each element one at a time. But it only removes [0] and [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'm doing now. To remove each element of the array, it is advisable to apply the method of shifting the array. For instance:
for each in (0..3)
a.shift
print a
end
This will shift the first element from the array and move each subsequent element forward one cell at a time. Thanks for the recommendation to use "everyone" - I see that this is the preferred syntax.
UPDATE 2 -
Will the next section of code be more representative of the correct ruby syntax?
(0..3).to_a.each do
a.shift
p a
end
.