Saturday, October 8, 2011

Ruby: for vs each

The difference is that #each scopes block variable inside the block, whereas for/in scopes it outside the block.

Following demonstration will clear this:

for i in [1,2,3]
# ...
end
puts i # => 3

[1,2,3].each do |j|
# ...
end
puts j # => NameError: undefined local...

Lets take one more example to demonstrate this:
loop1 = []
loop2 = []

calls = ["one", "two", "three"]

calls.each do |c|
loop1 << Proc.new { puts c }
end

for c in calls
loop2 << Proc.new { puts c }
end

loop1[1].call #=> "two"
loop2[1].call #=> "three"