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
/else
lets you branch your code based on conditionsunless
flips the conditioncase
is 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