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.
Last active
November 28, 2020 19:24
-
-
Save jelder/8284239 to your computer and use it in GitHub Desktop.
The difference between `for` and `each` in Ruby: scope.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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