This tutorial provides a step-by-step guide to understanding and using Ruby’s if/else control structures. You’ll learn the basics, explore advanced use cases, and apply your knowledge through engaging practice exercises.
Step 1: Introduction to if/else
The if/else statement is a fundamental control structure in Ruby that allows your program to make decisions based on conditions. It evaluates a condition and executes a block of code if the condition is true. If the condition is false, it can execute an alternative block of code using else.
if 10 > 5
puts '10 is greater than 5'
else
puts '10 is not greater than 5'
endPractice Exercise
Write a program that checks if a given number is positive. If it is, print 'Positive'. Otherwise, print 'Not positive'.
Show Solution
number = 7
if number > 0
puts 'Positive'
else
puts 'Not positive'
end
# Explanation: The program checks if the number is greater than 0 and prints 'Positive' if true. Otherwise, it prints 'Not positive'.Step 2: Using elsif for Multiple Conditions
When you have multiple conditions to evaluate, you can use elsif to chain additional conditions. This allows you to handle more complex decision-making scenarios.
age = 18
if age < 13
puts 'Child'
elsif age < 18
puts 'Teenager'
else
puts 'Adult'
endPractice Exercise
Write a program that categorizes a person's age into 'Child' (0-12), 'Teenager' (13-17), or 'Adult' (18+).
Show Solution
age = 15
if age < 13
puts 'Child'
elsif age < 18
puts 'Teenager'
else
puts 'Adult'
end
# Explanation: The program checks the age and prints the appropriate category based on the range it falls into.Step 3: Nested if/else Statements
You can nest if/else statements inside one another to handle more complex logic. This is useful when you need to evaluate conditions within conditions.
temperature = 25
if temperature > 20
if temperature > 30
puts 'It’s hot outside!'
else
puts 'It’s warm outside.'
end
else
puts 'It’s cold outside.'
endPractice Exercise
Write a program that checks if a number is even. If it is, check if it is also greater than 10. Print 'Even and greater than 10' or 'Even but not greater than 10' accordingly.
Show Solution
number = 14
if number % 2 == 0
if number > 10
puts 'Even and greater than 10'
else
puts 'Even but not greater than 10'
end
else
puts 'Not even'
end
# Explanation: The program first checks if the number is even. If true, it further checks if the number is greater than 10 and prints the appropriate message.Step 4: Ternary Operator for Concise if/else
Ruby provides a shorthand for simple if/else statements using the ternary operator (? :). This is useful for writing concise code when the logic is straightforward.
age = 20
status = age >= 18 ? 'Adult' : 'Minor'
puts statusPractice Exercise
Rewrite the following if/else statement using the ternary operator: if x > 5; puts 'Greater'; else; puts 'Less'; end.
Show Solution
x = 7
puts x > 5 ? 'Greater' : 'Less'
# Explanation: The ternary operator checks if `x` is greater than 5 and prints 'Greater' if true, otherwise 'Less'.Step 5: Using unless as an Alternative to if
The unless keyword is the opposite of if. It executes a block of code only if the condition is false. This can make your code more readable in certain scenarios.
raining = false
unless raining
puts 'Let’s go outside!'
else
puts 'Stay indoors.'
endPractice Exercise
Write a program that checks if a user is not logged in. If they are not, print 'Please log in'. Otherwise, print 'Welcome back!'.
Show Solution
logged_in = false
unless logged_in
puts 'Please log in'
else
puts 'Welcome back!'
end
# Explanation: The program uses `unless` to check if the user is not logged in and prints 'Please log in' if true.Step 6: Combining Conditions with Logical Operators
You can combine multiple conditions using logical operators like && (and), || (or), and ! (not). This allows you to create more complex decision-making logic.
age = 25
income = 50000
if age > 18 && income > 30000
puts 'Eligible for loan'
else
puts 'Not eligible'
endPractice Exercise
Write a program that checks if a user is eligible for a discount. The user must be either a student (check if is_student is true) or have a purchase amount greater than $100.
Show Solution
is_student = true
purchase_amount = 120
if is_student || purchase_amount > 100
puts 'Eligible for discount'
else
puts 'Not eligible'
end
# Explanation: The program checks if the user is a student or has a purchase amount greater than $100 and prints 'Eligible for discount' if either condition is true.Step 7: Real-World Example: User Authentication
Let’s apply what we’ve learned to a real-world scenario: user authentication. We’ll check if a user’s credentials are valid and provide appropriate feedback.
username = 'admin'
password = 'password123'
if username == 'admin' && password == 'password123'
puts 'Login successful!'
else
puts 'Invalid credentials.'
endPractice Exercise
Write a program that simulates a login system. Check if the username is 'user' and the password is 'secret'. If both are correct, print 'Access granted'. Otherwise, print 'Access denied'.
Show Solution
username = 'user'
password = 'secret'
if username == 'user' && password == 'secret'
puts 'Access granted'
else
puts 'Access denied'
end
# Explanation: The program checks if the username and password match the expected values and prints 'Access granted' if they do.Step 8: Advanced Challenge: Grade Calculator
Let’s tackle a more advanced problem: creating a grade calculator. The program will take a score and assign a grade based on predefined ranges.
score = 85
if score >= 90
puts 'A'
elsif score >= 80
puts 'B'
elsif score >= 70
puts 'C'
elsif score >= 60
puts 'D'
else
puts 'F'
endPractice Exercise
Write a program that calculates a student’s grade based on their score. Use the following ranges: A (90-100), B (80-89), C (70-79), D (60-69), F (0-59).
Show Solution
score = 78
if score >= 90
puts 'A'
elsif score >= 80
puts 'B'
elsif score >= 70
puts 'C'
elsif score >= 60
puts 'D'
else
puts 'F'
end
# Explanation: The program evaluates the score and assigns a grade based on the range it falls into.Sign in to take Cornell notes on this lesson — they save automatically and stay with your account.