Blocks, Procs & Lambdas
Ruby closures are implemented using Blocks, Procs, and Lambdas, allowing you to pass code snippets to methods as parameters.
1 yield, Procs, and Lambdas Visibility differences
Ruby provides three closure models:
- Block: Passed to methods implicitly, and executed using the **`yield`** keyword.
- Proc: Saved block objects. Procs do not validate parameter counts, and writing `return` inside a Proc exits the enclosing method immediately.
- Lambda: Strict block objects. Lambdas validate parameter counts explicitly, and writing `return` inside a lambda exits only the lambda itself.
2 Closures Code
Let's run a program demonstrating yield operations, Procs, and Lambdas:
Ruby — Closures & Blocks
▶ Run Code
# 1. Method with yield block
def execute_block
puts "Inside method"
yield if block_given?
puts "Exiting method"
end
execute_block { puts "--- Inside block ---" }
# 2. Proc vs Lambda
my_proc = Proc.new { |x, y| puts "Proc parameters: #{x}, #{y}" }
my_proc.call(10) # Ignores missing y parameter smoothly
my_lambda = ->(x, y) { puts "Lambda parameters: #{x}, #{y}" }
# my_lambda.call(10) # Throws ArgumentError! Requires exactly 2 parameters
my_lambda.call(10, 20)
3 Code Challenge
Challenge: Write a method called `perform_math` that yields two numbers to a block. Invoke the method with a block that multiplies the two numbers, and again with a block that adds them.