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| %>
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| %>
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
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.
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 -%>