This is Ruby. And Ruby knows how to block — like a bouncer for bad code. 🔥
Ruby Blocks — The Secret Sauce Behind Elegant Code
Picture this: You're writing Ruby. Things are going well… until you find yourself copying the same chunk of logic again. And again. And… wait, again? 😩
Enter: Ruby Blocks — your new BFF for clean, DRY, and elegant code. If methods are the skeleton of Ruby, blocks are the juicy muscles that flex logic in powerful ways.
🍱 Blocks? Like, Tupperware Blocks?
Exactly! Ruby blocks are like code Tupperware — you can pack them with logic, pass them around, and execute them on demand. They're anonymous chunks of code that you can hand over to a method to be called later.
🔍 Syntax: The Two Faces of Ruby Blocks
1. Curly Braces for the Quickies:
[1, 2, 3].each { |num| puts num }
2. do...end for Multiline Zen:
[1, 2, 3].each do |num|
puts "Double trouble: #{num * 2}"
end
Both are blocks. One's espresso; the other's a cappuccino. Same caffeine. Different vibe.
🚀 Meet yield: The Summoner
Wanna call the block from inside your method? Use yield. Think of it like saying: “Hey, block — your turn to shine!”
def greet
puts "Hello from method!"
yield
puts "Back in method!"
end
greet { puts "👋 Hello from the block!" }
✨ Why Use Blocks? Because We’re Not in 1998
- DRY code: Stop repeating yourself like a broken chatbot.
- Readable: Code reads like English (if English knew what
eachmeant). - Flexible: Pass logic around like it's no big deal — because in Ruby, it’s not.
💡 Real Power Play: Custom Methods with Blocks
def custom_timer(times)
times.times do |i|
yield(i)
end
end
custom_timer(3) do |i|
puts "Timer tick #{i + 1}"
end
😅 Common Rookie Mistakes
- Forgetting
yield: Your block won't run unless you call it! - Confusing blocks with Procs & Lambdas: Blocks are simpler — like casual flings. Procs and Lambdas? They're the long-term types.
- Not using
&blockwhen needed: Want to pass the block explicitly? Convert it using the&.
🧠 Mini Code Challenge
Write a method smart_each that takes an array and a block, and applies the block to each item. Not fancy, just functional.
def smart_each(arr)
arr.each { |item| yield(item) }
end
smart_each(["🍎", "🍌", "🍇"]) { |fruit| puts "Yum! #{fruit}" }
📌 Quick Recap
- Blocks are anonymous chunks of code — think: logic on-the-go.
- Use
do...endor{}depending on length and style. - Call them with
yieldor pass them using&block. - Ruby’s elegance? Yeah, blocks have a LOT to do with it.
🔗 Related Reads
🐦 Tweet-Sized Summary
Ruby blocks: the reusable logic capsules every dev should know. Learn how to yield like a pro and make your code DRY & elegant. #RubyLang
👀 Coming Up Next:
CodeCraft Diaries #6: Procs and Lambdas in Ruby — The Cousins You Need to Know

Comments
Post a Comment