Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between "each .. do" or "for .. in" loops in rails [duplicate]

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| %>
like image 773
daniel Avatar asked Feb 24 '11 23:02

daniel


2 Answers

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
like image 119
cam Avatar answered Sep 30 '22 08:09

cam


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.)
like image 37
DigitalRoss Avatar answered Sep 30 '22 08:09

DigitalRoss