The difference between "each .. do" or "for .. in" loops in the rails

Possible duplicate:
What is a "for" in Ruby

Hey. My question is that these loops are the same when I iterate over the array. Thanks for your time!

<% for track in @tracks %> 

or

 <% @tracks.each do |track| %> 
+6
loops ruby-on-rails ruby-on-rails-3
source share
3 answers

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

for does not 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 
+8
source share

Not

For the most part, you probably won't see the difference, but in these two cases the situation is completely different.

In one case, you have a loop directly in Ruby syntax; in the other case, traversing the data structure periodically gives way to a block.

  • return may work differently. If the external code is in lambda , then return will return from the lambda in the loop, but if it is executed in the block, it will return from the method of placing outside the lambda.
  • the lexical domain of identifiers created in the loop is different. (Generally speaking, you really shouldn't create things inside a structured language function and then use them later, but this is possible in Ruby with a loop, not a block.)
+3
source share

There is no difference. Just the difference in syntax.

What can make it different is to add elements to the block, such as a counter or more complex functions.

 <% @tracks.each do |i, track| -%> <% #i is your counter... just and example of adding more information in the block %> <% end -%> 
+1
source share

All Articles