"for" vs "each" in Ruby
This is the only difference:
each:
irb> [1,2,3].each { |x| } => [1, 2, 3]irb> xNameError: undefined local variable or method `x' for main:Object from (irb):2 from :0
for:
irb> for x in [1,2,3]; end => [1, 2, 3]irb> x => 3
With the for
loop, the iterator variable still lives after the block is done. With the each
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 the each
method.
When @collection
is nil
both loops throw an exception:
Exception: undefined local variable or method `@collection' for main:Object
See "The Evils of the For Loop" for a good explanation (there's one small difference considering variable scoping).
Using each
is considered more idiomatic use of Ruby.
Your first example,
@collection.each do |item| # do whateverend
is more idiomatic. While Ruby supports looping constructs like for
and while
, 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.