Aright so lets go back to the Array. Arrays act as a collection of items. These arrays are just blocks of memory linked together. In order to gain access to a particular part of an array we use an index. This index also acts as an offset into the array based off the start.
So if we had an Array and inside it contained 4 integers:
To get access to the third element we use the following code:
The semi-technical answer to this is that the computer finds the address in memory where aexample is located. Then it sees the index as the offset. In this case it's 2 so to get the proper element the computer adds to aexample's address, 2 * sizeof(element). Its hard to explain maybe I'll make some pictures later.
So now a 'for loop':
for i in 0..aexample.size
do_work(aexample[i])
end
That will loop 5 times. The results for i will be 0, 1, 2, 3, 4. All is fine and dandy until it goes to access aexample[4]. The valid indexes for accessing our four element array are 0,1,2,3. There is no such thing as an element at index 4. It's out of bounds for the array.
That's why the proper way to create a for loop that indexes an array would be this:
for i in 0..aexample.size - 1
do_work(aexample[i])
end
It might have been overkill to describe all this but I think it will help you better understand I hope.