The delete_at method deletes only array elements

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

.

+3
3

, 0, 1 2 .

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
+6

, , , , k.

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"]

0
["bat", "cat", "dog"]
1
["bat", "dog"]
2
["bat", "dog"]
3
["bat", "dog"]

k - 2, 2, 0 1.

PS. for. each, " Ruby-".

+5

, Firas Simone , , , , :

a.clear

a.slice!(0..3)

.

+2
source

Source: https://habr.com/ru/post/1781756/


All Articles