Skip to content

Instantly share code, notes, and snippets.

@chrp
Created October 28, 2013 10:09
Show Gist options
  • Save chrp/7194333 to your computer and use it in GitHub Desktop.
Save chrp/7194333 to your computer and use it in GitHub Desktop.
An example of how to manipulate (insert, delete) an array whilst iterating over it.
a = [1,2,3,4,5,6]
i = -1
while current = a[i+=1] do
prev_one = i==0 ? nil : a[i-1]
next_one = a[i+1]
#insert before without iterating over it
if current == 3 then
a.insert i, 2.5
i+=1
prev_one = a[i-1]
end
#insert after with iterating over it
if current == 5 then
a.insert i+1, 5.5
next_one = a[i+1]
end
#delete the next one without iterating over it
if current == 5.5 then
a.delete_at i+1
next_one = a[i+1]
end
puts "#{prev_one} <<< #{current} >>> #{next_one}"
end
puts "\nResult:"
puts a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment