(1)
My guess is that it is faster than the
for i in 0...array.size while slower than the
.each method.
My reasoning:
for i in 0...array.size
p array[i]
end
# Is pretty much equivalent to
(0...array.size).each {|i| p array[i]}
There are probably some variable scope issues if you tried that code, but you should get the idea.
You iterator over another object to get an object which is then used to retrieve an object from the array.
Accordingly to Blizzard the
.each is faster than using a for loop. How fast and if the different is significant I do not know. Though considering the different scope I can easily imagine that using
.each is faster.
(2)
There is no direct way to retrieve the index. You can use array.index(i) to retrieve the index, but not only is that slow, it only returns the index of the first matching value. Searching for elements in an array is so slow that in almost all cases using the
for i in 0...array.size way is faster. In addition it is easier to manage and keep track of.
Only use the iterator way (
for element in array) if the index is irrelevant.
If the index is relevant then you could this:
array.each_with_index {|element, index| p index, element}
If you want to know the .each method is implemented as the
Visitor PatternIt can be used on any
Enumerable collection.
There exist collections where the order the elements are retrieved can be stochastic and some where the concept of indexes doesn't make sense.
The index with the
.each_with_index method shows how many elements was retrieved before it.
*hugs*
- Zeriab