0Pricing
Ruby Academy · Lesson

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

The 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.call

All lessons in this course

  1. Blocks Recap
  2. Procs
  3. Lambdas
  4. Closures and Scope
← Back to Ruby Academy