Control Flow in Ruby — Teaching Your Code to Make Decisions
๐งญ CodeCraft Diaries #3: Control Flow in Ruby — Teaching Your Code to Make Decisions
“If coffee exists, drink it. Else, panic.”
Congratulations, you just wrote your first decision in Ruby.
Control flow is what gives your program a brain. It's how you get it to choose a path, evaluate a condition, and respond differently depending on what’s happening.
๐ฑ It Starts With a Question
In real life, we make decisions constantly:
- If it’s raining, take an umbrella.
- If your code runs, you celebrate. Else, you debug ๐ญ.
In Ruby, we do the same using keywords like if, elsif, else, and unless.
๐ If / Else in Action
weather = "rainy"
if weather == "sunny"
puts "Wear sunglasses ๐"
elsif weather == "rainy"
puts "Take an umbrella ☔"
else
puts "Check the weather app ๐คท"
end
Output: Take an umbrella ☔
Ruby reads that like a story. That’s the magic. ✨
๐ซ Unless – Flip the Logic
Sometimes it’s easier to say “do this unless X happens.” Ruby gives you the unless keyword for that:
logged_in = false
unless logged_in
puts "Please log in first ๐"
end
Think of it as “if NOT.” It’s clean and very Ruby-ish.
✅ Comparison Operators: The Brains of Decisions
==→ Equal to!=→ Not equal to>,<→ Greater/Less than>=,<=→ Greater/Less or equal
age = 18
if age >= 18
puts "You're eligible to vote ๐ณ️"
end
๐ Case Statement – When You Have Many Options
role = "admin"
case role
when "admin"
puts "Full access granted ✅"
when "editor"
puts "Edit access only ✍️"
when "viewer"
puts "View only ๐"
else
puts "No access ๐ซ"
end
Use case when you want to match one value against many choices.
๐ฏ Quick Real-World Use
user_logged_in = true
cart_items = 0
if user_logged_in && cart_items > 0
puts "Proceed to checkout ๐"
elsif user_logged_in
puts "Your cart is empty ๐"
else
puts "Please log in to continue ๐"
end
This is the kind of logic behind real websites. Ruby makes it clear and readable.
๐ Pro Tip
"Your code should read like a conversation."
If someone else (or future-you) can’t tell what your condition is doing, rewrite it. Code is for humans, too.
๐ธ Visual Vibe
๐ ️ TL;DR
if/elselets you branch your code based on conditionsunlessflips the conditioncaseis great for handling many options- Use
==,>,!=to compare values
Your Ruby journey just learned to think. Next up: it'll learn to repeat ๐
๐ Missed the Last Blog?
Check out Variables and Data Types in Ruby — where the real magic started:
๐
https://codecraftdiaries.blogspot.com/2025/05/variables-and-data-types-in-ruby.html

Comments
Post a Comment