I just had a quick question regarding loops in Ruby. Is there a difference between these two ways of iterating through a collection?
# way 1
@collection.each do |item|
# do whatever
end
# way 2
for item in @collection
# do whatever
end
Just wondering if these are exactly the same or if maybe there’s a subtle difference (possibly when @collection is nil).
This is the only difference:
each:
for:
With the
forloop, the iterator variable still lives after the block is done. With theeachloop, it doesn’t, unless it was already defined as a local variable before the loop started.Other than that,
foris just syntax sugar for theeachmethod.When
@collectionisnilboth loops throw an exception: