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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With