I’ve made a very small ruby script today that makes use of regexes to track down certain content in files with a specific name and removes that content before adding its replacement. (Or else stuff would go wrong during iterations).
I’m not very used to ruby (only been using it since my vacation job started which is 1-2 weeks ago), but one of my habits is to avoid touching lists (or most other ADT’s using indexes) while iterating over them (to remove the certain content), doesn’t matter which language I’m using.
After some searching I found out about a few Array functions that could help. Right now, I’m using Array.reject! and the script works like I want it to work, but I honestly can’t figure out why Array.reject! {|line| line =~ regex } does not have trouble with skipping objects in the array. These sources, ruby-docs & some random website, confirm that the changes are applied instantly while iterating, which makes me wonder how it does not mess up… The lines that are being removed have no space/words between them, only \n brings the next one to its own line of course (but that’s just part of the end of the strings).
Has anyone got a great explanation for this?
Array#reject!uses aforloop to iterate over the array’s elements. Here’s the C code:The interesting part is that
iis not incremented in theforstatement. If the block given toreject!evaluates totruethe current element is removed andary[i]automatically points to the next element. Only if it evaluates tofalse,iis incremented.