Skip to content

Instantly share code, notes, and snippets.

@jelder
Last active November 28, 2020 19:24
Show Gist options
  • Save jelder/8284239 to your computer and use it in GitHub Desktop.
Save jelder/8284239 to your computer and use it in GitHub Desktop.
The difference between `for` and `each` in Ruby: scope.

for should only be used when you actually want the iteratee to be accessible after you leave the block. for pollutes the parent scope with old iteratees. For this reason, each should be your default.

[1,2,3].each do |i|
puts "Inside each loop: #{i}"
end
puts "Outside each loop: #{i}" # => undefined local variable or method `i' for main:Object (NameError)
for i in [1,2,3]
puts "Inside for loop: #{i}"
end
puts "Outside for loop: #{i}" # => prints "Outside for loop: 3"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment