When to use `for x in y`and when to use `each`

Asked

Viewed 146 times

-2

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

Now, I ask, when should I use each of them? Could give some examples of cases where one should use one and other cases where one should use the other?

1 answer

3


I think the other question already answers that, doesn’t it? The only difference between the two is that in the for the variable that is used to make the iteration continues in scope when the for ends.

Internally the for is equal to each. I personally prefer the each because it does not leave side effects and because it seems more "natural" within the style of Ruby. The for could be preferred if there was some 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 in legibility. If there is no performance gain, one should always prefer the most readable and simplest code. I believe that choosing between one or the other is a matter of style. Ruby programmers often prefer each, but beginner programmers who come from other languages like Javascript may initially find it easier to understand the for.

  • The question is a little different. It’s one thing to know the difference. It’s another to have examples of use. I understand that for keeps the variable out of scope, but I can’t see real cases where it’s useful.

  • @fotanus In fact the for is rarely used in Ruby. I don’t remember seeing it other than in examples.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.