7

Possible Duplicate:
What is “for” in Ruby

Hey. My question is if these loops are the same when I iterate through an Array. Thx for your time!

<% for track in @tracks %>

or

<% @tracks.each do |track| %>
Community
  • 1
  • 1
daniel
  • 3,105
  • 4
  • 39
  • 48

3 Answers3

9

They are different (although it may not matter for your purposes).

for doesn't create a new scope:

blah = %w(foo bar baz)
for x in blah do
   z = x
end
puts z # "baz"
puts x # "baz"

.each creates a new scope for the block:

blah.each { |y| a = y }
puts a # NameError
puts y # NameError
cam
  • 14,192
  • 1
  • 44
  • 29
  • What do you mean by new scope? – thenengah Feb 25 '11 at 00:03
  • 2
    @Sam: http://en.wikipedia.org/wiki/Scope_(programming) Notice how the `x` and `z` variables in my example can be accessed after the `for` loop, but `a` and `y` cannot be accessed outside of the block passed to `each`. – cam Feb 25 '11 at 00:09
3

No

For the most part, you probably won't see any differences, but things are quite different in those two cases.

In one case, you have a loop directly in Ruby syntax, in the other case a data structure traversal is periodically yielding to a block.

  • return may work differently. If the outer code is in a lambda then return will return from the lambda within the loop but if executed within a block it will return from the enclosing method outside the lambda.
  • The lexical scope of identifiers created within the loop is different. (On general principles you really shouldn't create things inside a structured language feature and then use them later outside but this is possible in Ruby with the loop and not with the block.)
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
1

There is no difference here. Just a difference in syntax.

What could make this different is adding elements to the block such as a counter, or more advanced features.

<% @tracks.each do |i, track| -%>
    <% #i is your counter... just and example of adding more information in the block %>
<% end -%>
thenengah
  • 42,557
  • 33
  • 113
  • 157