Created
November 11, 2009 19:10
-
-
Save piyo/232202 to your computer and use it in GitHub Desktop.
ruby example about closure
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
| #!/usr/bin/ruby | |
| def get_a_closure | |
| this_var_is_captured = 1 | |
| return_this_function = Proc.new do |x,y| | |
| puts "#{this_var_is_captured} #{x} #{y}" | |
| end | |
| return_this_function | |
| end | |
| def run_my_closure | |
| a_closure = get_a_closure() | |
| a_closure.call(2, 3) | |
| # outputs 1 2 3 | |
| # the this_var_is_captured is still 1 despite not being "in scope" on the stack | |
| this_var_is_captured = 4 | |
| a_closure.call(2, 3) | |
| # outputs 1 2 3 | |
| # having a local var with the same name does not affect the closure | |
| # because ruby is not dynamic scope | |
| end | |
| if __FILE__ == $0 | |
| run_my_closure | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment