Closures and Scope
Capturing variables.
Capturing Variables
A closure is a function that remembers the variables from the place where it was defined, even after that place has finished running. Procs and lambdas are closures.
name = "Ada"
greeter = -> { puts "Hello, #{name}" }
greeter.callThe Variable Travels With It
The closure does not copy the value; it keeps a live reference to the variable. Change the variable later and the closure sees the new value.
count = 0
reader = -> { count }
count = 5
puts reader.callAll lessons in this course
- Blocks Recap
- Procs
- Lambdas
- Closures and Scope