Meet Ruby’s Secret Siblings: Procs & Lambdas Made Fun
Procs and Lambdas in Ruby — The Cousins You Need to Know
Published on June 09, 2025 • CodeCraft Diaries #6
"If methods are the parents and blocks are the kids, then Procs and Lambdas are the cool cousins who show up late but save the day with reusable logic."
π Wait... Blocks Have Relatives?
Yes, they do. Blocks are amazing, but sometimes you want to reuse them, store them in variables, or pass them around like a tray of samosas at a tech meetup.
That’s where Procs and Lambdas come in — Ruby’s way of giving blocks a full-time job.
πΆ Quick Recap: What’s a Block?
def greet
yield
end
greet { puts "Hello from the block!" }
Blocks are anonymous chunks of code you can pass to methods. But blocks can’t live on their own — Procs and Lambdas can.
π§π€π§ Meet Proc and Lambda
π¦ What is a Proc?
A Proc is like a block with a backpack — you can carry it around and call it whenever you want.
say_hi = Proc.new { puts "Hi there!" }
say_hi.call # Hi there!
π¦Έ What is a Lambda?
Lambdas are like Procs... but with manners.
say_bye = lambda { puts "Goodbye!" }
say_bye.call # Goodbye!
You can also use the arrow syntax:
say_hello = -> { puts "Hello!" }
say_hello.call
⚖️ Proc vs Lambda — Spot the Differences
- Return behavior: Procs return from the enclosing method, Lambdas return from themselves.
- Argument check: Lambdas care about the number of arguments. Procs don’t.
π Return Example:
def test_proc
my_proc = Proc.new { return "Returned from Proc" }
my_proc.call
"Returned from method"
end
puts test_proc # Output: Returned from Proc
def test_lambda
my_lambda = -> { return "Returned from Lambda" }
my_lambda.call
"Returned from method"
end
puts test_lambda # Output: Returned from method
π§ Use Cases — Why Even Bother?
- Reusable callbacks
- Validation logic
- Cleaner control flows
π§ͺ Mini Code Challenge
Write a method that accepts a lambda and calls it.
def perform_action(action)
puts "Starting..."
action.call
puts "Done!"
end
shout = -> { puts "π₯ Boom!" }
perform_action(shout)
π¨ Common Mistakes
- Using return inside a Proc and wondering why the method exits
- Passing wrong arguments to Lambdas
- Confusing blocks, Procs, and Lambdas as “the same”
π‘ Quick Recap
- Block: Can’t be saved, passed anonymously to methods
- Proc: Can be saved and reused, flexible but loose
- Lambda: Like Proc but strict and polite
π¦ Tweet-sized Summary
Procs and Lambdas in Ruby: Reusable blocks that let you DRY up code, add elegance, and get strict if needed. Don’t fear them — master them. π»
π§ Read Previous Diaries
π Coming Up Next
CodeCraft Diaries #7: “Modules & Mixins in Ruby — Sharing is Caring (But Make It Clean)”

Comments
Post a Comment