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
each
meant). - 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
&block
when 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...end
or{}
depending on length and style. - Call them with
yield
or 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