Difference between for and someclass.each do |var|

T

Tyrel R.

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
 
R

Robert Klemme

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=3D%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

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 
Y

Y. NOBUOKA

Hi,
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,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top