When to use 'for x in y' and when to use 'each' [duplicate]

-2
    

This question already has an answer here:

    

In my other question I found out the difference between for x in y and method each .

Now, I ask: When should I use each one of them? Could you give examples of cases where you should use one and other cases where you should use the other?

    
asked by anonymous 18.02.2014 / 15:03

1 answer

3

I think the other question already answers this, does not it? The only difference between the two is that in for the variable that is used to do the iteration continues in scope when for ends.

Internally, for is equal to each . I personally prefer each because it leaves no side effects and because it seems more "natural" within the Ruby style. for could be preferred if there was any intention to use the variable after the loop, to return the last element or something. But it can also be argued that this does not help with legibility. If there is no performance gain, one should always prefer the more readable and simpler code. I believe that choosing between one or the other is a matter of style. Ruby programmers usually prefer each , but beginner programmers who come from other languages like JavaScript may initially find it easier to understand for .

    
18.02.2014 / 15:53