-
-
Save pvin/8ee64df82c638adca0f32e35d2d6498a to your computer and use it in GitHub Desktop.
Carefull with processing array index, ruby. (reference : Eloquent ruby)
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
#The easiest way to screw up one of these iterating methods is to change the collection out from underneath the method. | |
#Here, for example, is a seriously misguided attempt to remove all of the negative numbers from an array: | |
array = [ 0, -10, -9, 5, 9 ] | |
array.each_index {|i| array.delete_at(i) if array[i] < 0} | |
pp array | |
#The trouble with this code is that it will tend to leave some negative numbers behind: Removing the first one (the -10 ) from | |
#the array messes up the internal indexing of the each method, so much that it will miss the second negative number, leaving | |
#us with a result of: | |
[0, -9, 5, 9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment