Created
October 28, 2013 10:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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