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.
Initially:
[ant, bat, cat, dog]
a.delete_at[0] => ant
[bat, cat, dog]
go to next element -> 1
a.delete_at[1] => cat
[bat, dog]
go to next element -> 2
a.delete_at[2] => nil (out of range)
go to next element -> 3
a.delete_at[3] => nil
Because you are deleting the array in place, and the third time the execution enter the loop, your array is shorter than the value of k.
Try to execute
a=%w(ant bat cat dog)
puts a.inspect #output: ["ant", "bat", "cat", "dog"]
for k in (0..3).to_a
p k
a.delete_at(k)
p a
end
puts a.inspect #output: ["bat", "dog"]
Here's the output
0
["bat", "cat", "dog"]
1
["bat", "dog"]
2
["bat", "dog"]
3
["bat", "dog"]
When k is 2, you are trying to delete the element at index 2 but your array is only composed by 2 elements with indexes 0 and 1.
PS. Avoid using for. Use each instead, is "more Ruby-oriented".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With