For vs Each in Ruby

One of the discussions I was involved in at RubyFuza revolved around the difference between for and each in Ruby. There is only a subtle difference around scoping, but I think it’s an important distinction because it reveals some important aspects of Ruby.

The for loop is a syntax construct, similar to the if statement. Whatever variable you define in the for loop will remain after the loop as well.

list = %w{ google yahoo bing duckduckgo }

for engine in list
  # do something with engine
end
puts engine
# duckduckgo

On the other hand, Enumerable#each is a method which receives a block. A block introduces a new lexical scope, so any variables we declare in the block will not be around after the block executes.

list = %w{ google yahoo bing duckduckgo }

list.each do |engine|
  # do something with engine
end
puts engine
# NameError: undefined local variable or method ‘engine’

The for loop is very rarely used in Ruby. I don’t think it’s that bad to be using it, but the each method does decrease the possibility of side effects.