Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 The Relationship Between "each" and "for"
Index -> Programming, Ruby -> Ruby Tutorials
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: Wed Jul 13, 2005 10:45 pm   Post subject: The Relationship Between "each" and "for"

It's the question that's as old as any I can remember. Should I use "for" or should I use the "each" method?

To answer that on a case-by-case basis, we have to understand both ways, how they're similar, and how they differ.

The "for" loop is made possible by the "each" method. Any class which implements "each" can use the for loop. Let's look at a simple nonsense example.

code:
class Qux
   def each
      yield 37
      yield 53
      yield 78
   end
end


Now I can just:

code:
for x in Qux.new
   puts x
end


And of course, I can call "each" directly.

code:
Qux.new.each { |x| puts x }


So, what's the difference, except that "for" looks a bit nicer for long loops, and "each" has a certain charm for the simple stuff?

Scope is the issue. A variable created inside of a "for" loop is still in scope when the loop finishes. However, variables created within blocks attached to calls to "each" are local to the block, and don't affect the outer scope.
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> Programming, Ruby -> Ruby Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: