Last active
December 17, 2015 18:29
-
-
Save beala/5653352 to your computer and use it in GitHub Desktop.
Proc (block) and function scoping are different. wat.
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
def printer x | |
def helper | |
puts x | |
end | |
helper | |
end | |
printer "test" # NameError: undefined local variable or method `x' for main:Object | |
def printer x | |
helper = Proc.new do | |
puts x | |
end | |
helper.call | |
end | |
printer "test" # test. It works! | |
# Nested function definitions do not capture variables from the outer scope, but Procs (blocks) do. Why, Ruby, why? |
Why is it useful for a block to capture variables, but not for an inner function?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This makes sense to me.
A Proc/block includes a closure of it's scope (it's big part of what makes them so useful).
A method on the other hand does not, it would be inefficient, wouldn't have a use, and might interfere with other behavior (and if you need the closure you can use a Proc/block).