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
for
loop, the iterator variable still lives after the block is done. With theeach
loop, it doesn't, unless it was already defined as a local variable before the loop started.Other than that,
for
is just syntax sugar for theeach
method.When
@collection
isnil
both loops throw an exception:Your first example,
is more idiomatic. While Ruby supports looping constructs like
for
andwhile
, the block syntax is generally preferred.Another subtle difference is that any variable you declare within a
for
loop will be available outside the loop, whereas those within an iterator block are effectively private.It looks like there is no difference,
for
useseach
underneath.Like Bayard says, each is more idiomatic. It hides more from you and doesn't require special language features. Per Telemachus's Comment
for .. in ..
sets the iterator outside the scope of the loop, soleaves
a
defined after the loop is finished. Where aseach
doesn't. Which is another reason in favor of usingeach
, because the temp variable lives a shorter period.