Skip to content

Instantly share code, notes, and snippets.

@beala
Last active December 17, 2015 18:29
Show Gist options
  • Save beala/5653352 to your computer and use it in GitHub Desktop.
Save beala/5653352 to your computer and use it in GitHub Desktop.
Proc (block) and function scoping are different. wat.
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?
@khalsah
Copy link

khalsah commented May 27, 2013

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).

@beala
Copy link
Author

beala commented May 27, 2013

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