Re: Looping through array, deleting elements



Alle giovedì 8 marzo 2007, dkmd_nielsen ha scritto:
My idea of looping through an array, interrogating elements that are
of class instruction, and deleting the element does not appear to work
as I thought. I think I know why. What is the best solution?

block.each {|i| ab.delete(i) if i.parm == "FOO"}

where block is a series of elements of class instruction(i). Class
instruction has two attributes, parm and arg. If the instruction parm
is FOO, then delete the instruction object from the array and keep
looping. Half of what should be deleted actually get's deleted. I
think the reason is: the loop is looking at element x foo, element x
foo get's deleted, the array is shifted left, array pointer has not
changed but is now referencing element y foo, loop advances the array
pointer, and now array pointer is pointing at element z foo.

If what I think is correct, what is the best solution? Do I set the
current element to nil, then compact the array after the loop? Do I
delete the instruction and then do a redo? Or is there a better
solution than those?

Thanks,
dvn

I'm not sure I understand your code (what is that ab in the each block?) At
any rate, there's method which directly deletes the elements of an array
which satisfy a given condition: Array#delete_if:

a=[1,2,3,4,5,6]
a.delete_if{|i| i > 3}
=> [1,2,3]

This method passes each element of the array to the block, then deletes it if
the block returns true.

Stefano

.



Relevant Pages

  • Re: Looping through array, deleting elements
    ... instruction has two attributes, parm and arg. ... the loop is looking at element x foo, ... foo get's deleted, the array is shifted left, array pointer has not ... and now array pointer is pointing at element z foo. ...
    (comp.lang.ruby)
  • Re: sub esp, 0ch question
    ... No, if it was a char array, the length would be 192. ... The rep stos ... rep stos instruction does this all in one shot as opposed to setting ... that Debug builds have a minimum local stack size so that recursion ...
    (microsoft.public.win32.programmer.kernel)
  • Looping through array, deleting elements
    ... My idea of looping through an array, ... instruction has two attributes, parm and arg. ... the loop is looking at element x foo, ...
    (comp.lang.ruby)
  • Re: Looping through array, deleting elements
    ... instruction has two attributes, parm and arg. ... the loop is looking at element x foo, ... foo get's deleted, the array is shifted left, array pointer has not ... and now array pointer is pointing at element z foo. ...
    (comp.lang.ruby)
  • Re: Looping through array, deleting elements
    ... You are modifying the array as you iterate over it ... instruction has two attributes, parm and arg. ... the loop is looking at element x foo, ... and now array pointer is pointing at element z foo. ...
    (comp.lang.ruby)