Difference between for and someclass.each do |var|

Hello everyone,

I come from the low level C land and I am really loving ruby but I am
trying to understand its behaviour.

Can anyone tell me if there is something different going on under the
hood between these two loops.

for var in class.each do
#stuff
end

class.each do |var|
#stuff
end

Hej Tyrel,

it is just syntatical sugar. Both are essentially equal.
The only difference is that each is a method of an Enumerable.

Best,
Sebastian

Thank you its all starting to steep in…I think

On Tue, Mar 22, 2011 at 11:15 AM, Sebastian Grl
[email protected] wrote:

it is just syntatical sugar. Both are essentially equal.
The only difference is that each is a method of an Enumerable.

That’s not true. There is also a scoping difference:

11:43:58 ~$ ruby <<CODE
a=%w{foo bar}
for e in a
p e
end
p e
a.each do |x|
p x
end
p x
CODE

“foo”
“bar”
“bar”
“foo”
“bar”
-:9: undefined local variable or method `x’ for main:Object (NameError)
11:44:19 ~$

A block opens a new scope wile for doesn’t.

I believe there is also a slight runtime difference but that really
only matters if you need to squeeze the last bit of performance out of
your application.

Kind regards

robert

Hi,

for var in class.each do
#stuff
end

class.each do |var|
#stuff
end

it is just syntatical sugar. Both are essentially equal.
The only difference is that each is a method of an Enumerable.

In a for/in loop, you need not call #each method.
I think following two code snippets are mostly equal.

the #each method call isn’t needed

for var in obj do

stuff

end

mostly equivalent to the previous snippet

obj.each do |var|

stuff

end

Note:
A #each method returns a Enumerator object if you don’t provide a block.

~$ irb
ruby-1.9.2-p136 :001 > [].each # provide no block
=> #<Enumerator: []:each>
ruby-1.9.2-p136 :002 > [].each {} # provide a block
=> []

Regards,

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs