Iterators in Ruby — Think Less Looping, More Logic
Ruby Iterators — When Loops Just Aren’t Elegant Enough
Published: June 24, 2025 • CodeCraft Diaries #7
"If you've been writing `for` loops in Ruby like it's 1999, this one's for you."
Let’s be real: loops are the bread and butter of programming. But in Ruby? You don’t just butter the bread — you toast it, drizzle it with honey, and serve it like a gourmet dev snack.
Welcome to the elegant world of Ruby iterators — where looping is expressive, concise, and kinda beautiful.
🚶 Why Not Just Use a Loop?
You can, of course:
for i in 1..3
puts i
end
But Ruby gives us cooler tools. Imagine replacing that clunky loop with something like:
(1..3).each { |i| puts i }
Cleaner. Readable. Ruby-esque.
🔄 Meet Your Iterator Friends
1. each
— The Friendly Tour Guide
["coffee", "code", "chai"].each do |item|
puts "I love #{item}"
end
Perfect for walking through arrays, hashes, or ranges.
2. map
— The Transformer
numbers = [1, 2, 3]
squared = numbers.map { |n| n * n }
puts squared.inspect # [1, 4, 9]
Pro Tip: Use map when you want to return a transformed array.
3. select
— The Filter Master
scores = [10, 20, 30, 5]
high_scores = scores.select { |s| s > 15 }
puts high_scores.inspect # [20, 30]
4. times
— The Minimalist Loop
3.times { puts "Ping!" }
When all you need is repetition and vibes.
🧠 But Wait... How Do These Work?
Under the hood, iterators work by accepting blocks of code. Like:
def custom_each(array)
for item in array
yield(item)
end
end
custom_each(["a", "b"]) { |x| puts x }
That's right — iterators yield to blocks, giving you the power to inject logic right in.
🤯 Real-World Example
Imagine you’re filtering logged-in users who are also admins:
users = [
{ name: "Alice", admin: true },
{ name: "Bob", admin: false }
]
admins = users.select { |u| u[:admin] }
puts admins.inspect
Elegant, right? No `if`, `then`, `break`, or noise.
🚧 Common Beginner Pitfalls
- Forgetting that
map
returns a new array — it doesn’t modify the original. - Using
each
when you really needmap
orselect
. - Trying to
return
from inside a block without understanding how `yield` works.
🧪 Mini Challenge
Write a Ruby method that accepts an array and prints only the items longer than 5 characters using select
.
def long_words(words)
long = words.select { |w| w.length > 5 }
puts long
end
long_words(["ruby", "developer", "code", "iteration"])
📚 Quick Recap
each
→ Go through every item.map
→ Transform each item and get a new array.select
→ Filter items that match a condition.times
→ Repeat something N times.
🔗 Related CodeCraft Diaries
- Procs and Lambdas in Ruby — The Cousins You Need to Know
- Ruby Blocks — The Secret Sauce Behind Elegant Code
🪄 Coming Up Next
CodeCraft Diaries #8: “Modules & Mixins in Ruby — Sharing is Caring (Without the Mess)”
Comments
Post a Comment