Skip to content

Instantly share code, notes, and snippets.

@piyo
Created November 11, 2009 19:10
Show Gist options
  • Select an option

  • Save piyo/232202 to your computer and use it in GitHub Desktop.

Select an option

Save piyo/232202 to your computer and use it in GitHub Desktop.
ruby example about closure
#!/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