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