Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: What is the difference between a for loop and an each loop? [duplicate]

Possible Duplicate:
for vs each in Ruby

Let's say that we have an array, like

sites = %w[stackoverflow stackexchange serverfault]

What's the difference between

for x in sites do
  puts x
end

and

sites.each do |x|
  puts x
end

?

They seem to do the same exact thing, to me, and the syntax of the for loop is clearer to me. Is there a difference? In what situations would this be a big deal?

like image 415
eckza Avatar asked Apr 15 '11 12:04

eckza


People also ask

What is for loop in Ruby?

In Ruby, for loops are used to loop over a collection of elements. Unlike a while loop where if we're not careful we can cause an infinite loop, for loops have a definite end since it's looping over a finite number of elements.

How does for loop work in Ruby?

Ruby until loop will executes the statements or code till the given condition evaluates to true. Basically it's just opposite to the while loop which executes until the given condition evaluates to false. An until statement's conditional is separated from code by the reserved word do, a newline, or a semicolon.

How do you break out of a loop in Ruby?

In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.


1 Answers

There is a subtle difference regarding scoping, but I would recommend understanding it well as it reveals some of important aspects of Ruby.

for is a syntax construct, somewhat similar to if. Whatever you define in for block, will remain defined after for as well:

sites = %w[stackoverflow stackexchange serverfault]
#=> ["stackoverflow", "stackexchange", "serverfault"]

for x in sites do
  puts x
end
stackoverflow
stackexchange
serverfault
#=> ["stackoverflow", "stackexchange", "serverfault"]
x
#=> "serverfault"

On the other hand, each is a method which receives a block. Block introduces new lexical scope, so whatever variable you introduce in it, will not be there after the method finishes:

sites.each do |y|
  puts y
end
stackoverflow
stackexchange
serverfault
#=> ["stackoverflow", "stackexchange", "serverfault"]
y
NameError: undefined local variable or method `y' for #<Object:0x855f28 @hhh="hello">
    from (irb):9
    from /usr/bin/irb:12:in `<main>'

I would recommend forgetting about for completely, as using each is idiomatic in Ruby for traversing enumerables. It also recspects the paradigm of functional programming better, by decreasing chances of side-effects.

like image 161
Mladen Jablanović Avatar answered Oct 14 '22 23:10

Mladen Jablanović