Delete array element within iterator block?

J

Jari Williamsson

How do I (in an elegant way) delete an element of an array within a
block, while using a block iterator?

The code below won't work (the wanted behavior here is to get all array
elements to print and but also delete the 2nd element after it has been
encountered):
---
arr = [1,2,3,4]
arr.each_with_index { |e, i|
p e
arr.delete_at(i) if i == 1
}
---
results in:
1
2
4

Of curse, I could loop and keep track of the index manually, but I'm
mainly checking if there is any built-in stuff here.


Best regards,

Jari Williamsson
 
S

Sharon Phillips

How do I (in an elegant way) delete an element of an array within a
block, while using a block iterator?
I assume using delete_if is no good in this situation?
[1,2,3,4,5,6].delete_if{|i| i>4}
[1,2,3,4]
The code below won't work (the wanted behavior here is to get all
array elements to print and but also delete the 2nd element after it
has been encountered):
---
arr = [1,2,3,4]
arr.each_with_index { |e, i|
p e
arr.delete_at(i) if i == 1
}
---
results in:
1
2
4
This is interesting, because although the results printed on the
screen imply the 3 was removed, if you look at the array afterthe
operation you'll see it was the 2 removed (as we wanted)

irb(main):013:0> (a=[1,2,3,4]).each_with_index{|e,i| p
e;a.delete_at(i) if i==1}
1
2
4
=> [1, 3, 4]

I've no ideas why

Cheers,
Dave
 
D

David A. Black

HI --

How do I (in an elegant way) delete an element of an array within a block,
while using a block iterator?
I assume using delete_if is no good in this situation?
[1,2,3,4,5,6].delete_if{|i| i>4}
[1,2,3,4]
The code below won't work (the wanted behavior here is to get all array
elements to print and but also delete the 2nd element after it has been
encountered):
---
arr = [1,2,3,4]
arr.each_with_index { |e, i|
p e
arr.delete_at(i) if i == 1
}
---
results in:
1
2
4
This is interesting, because although the results printed on the screen imply
the 3 was removed, if you look at the array afterthe operation you'll see it
was the 2 removed (as we wanted)

irb(main):013:0> (a=[1,2,3,4]).each_with_index{|e,i| p e;a.delete_at(i) if
i==1}
1
2
4
=> [1, 3, 4]

I've no ideas why

First time through:

a => [1,2,3,4]
e => 1
i => 0

Second time through:

a => [1,2,3,4]
e => 2
i => 1

Third time through:

a => [1,3,4]
e => 4 # i.e., a[2]
i => 2

Or some such thing. Of course the best idea is never to do this :)


David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top