Loops: Each vs For

If you have spent some time around ruby, you probably have noticed that you do not see the for loop very often. Typically most rubyists use the each loop. And the for loop actually uses each. Yet there is one difference that can land you in trouble.

Take the each loop:

1
2
3
4
5
  [1, 2, 3].each{|x| p x}

  => 1
  => 2
  => 3

And now the for loop:

1
2
3
4
5
6
7
  for i in [1, 2, 3]
    p i
  end

  => 1
  => 2
  => 3

Looks pretty straight forward, right? Now lets introduce a local variable.

1
2
3
4
5
6
7
8
9
10
11
12

  x = 'test'

  [1, 2, 3].each{|x| p x}

  => 1
  => 2
  => 3

  p x

  => 'test'

And now the for loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
  i = 'test'

  for i in [1, 2, 3]
    p i
  end

  => 1
  => 2
  => 3

  p i

  => 3

As you can see, we no longer have our local variable set to ‘test’ when using the for loop. But using the each loop preserves this variable.