Posts

Showing posts with the label Ruby Basics

Iterators in Ruby — Think Less Looping, More Logic

Image
Ruby Iterators — When Loops Just Aren’t Elegant Enough 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 ...

This is Ruby. And Ruby knows how to block — like a bouncer for bad code. 🔥

Image
Ruby Blocks — The Secret Sauce Behind Elegant 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. ...

Loops in Ruby — Teaching Your Code to Repeat

CodeCraft Diaries #4: Loops in Ruby — Teaching Your Code to Repeat CodeCraft Diaries #4: Loops in Ruby — Teaching Your Code to Repeat "Why did the Ruby developer go in circles? Because they couldn't break the loop!" Welcome back, CodeCrafters! 🎉 In our last adventure, we taught our code to make decisions using control flow. Now, it's time to teach it to repeat tasks efficiently. Let's dive into the world of loops in Ruby! 🔁 The Need for Loops Imagine you want to print "Hello, World!" five times. You could write: puts "Hello, World!" puts "Hello, World!" puts "Hello, World!" puts "Hello, World!" puts "Hello, World!" But that's not efficient. Instead, let's use a loop: 5.times do puts "Hello, World!" end Much better, right? 🌀 Types of Loops in Ruby 1. while Loop Repeats as long as a condition is true. i = 0 while i ...