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