Posts

Showing posts with the label De Community

Why Your Ruby Scripts Keep Breaking Files (and How to Fix Them)

File Handling in Ruby — Reading, Writing, and What Could Go Wrong File Handling in Ruby — Reading, Writing, and What Could Go Wrong CodeCraft Diaries #9 • For Freshers, Students & Curious Developers “If you’ve never accidentally deleted a file while testing your script, are you even a developer?” Working with files is one of the first real-world things you’ll do in any programming language. Whether it's reading a config, logging errors, or saving user data — file I/O is everywhere. And Ruby? Ruby makes it refreshingly simple. Until you forget to close the file... 💀 📖 Reading from a File Let’s say we have a file called data.txt . File.open("data.txt", "r") do |file| puts file.read end What’s happening here? "r" means “read mode” file.read grabs the entire content The block auto-closes the file (thank you, Ruby!) ✍️ Writing to a File File.open("log....

Because Copy-Pasting Is Not Coding - Ruby Loops Tutorial

Image
Loops in Ruby — Because Repeating Manually Is So 2000s | CodeCraft Diaries #4 Loops in Ruby — Because Repeating Manually Is So 2000s Imagine being told to print “I love Ruby” 100 times by hand. Sounds painful, right? Well, that’s what we used to do before loops existed (not really, but you get the point 😉). In today’s edition of CodeCraft Diaries , we’ll explore the magic of loops in Ruby — tools that make repetition effortless, elegant, and DRY (Don’t Repeat Yourself). Why Loops Matter Loops allow your code to execute a block repeatedly based on a condition or a set number of times. They're essential when you're handling lists, user input, data processing, and more. 1. while Loop The while loop runs as long as the condition is true . i = 0 while i Common mistake: Forgetting to increment the loop variable, which causes an infinite loop. 2. until Loop Think of until as the opposite of while — it runs until the cond...