Ruby offers many ways to control the flow of a program to make coding easier and more flexible. Different styles help programmers write clear and simple code for different situations.
0
0
Why Ruby has multiple control flow styles
Introduction
When you want to choose between different actions based on conditions, like checking user input.
When you need to repeat a task multiple times, such as processing items in a list.
When you want to write short, simple decisions in one line for quick checks.
When you want to handle multiple possible cases clearly, like menu options.
When you want to make your code easier to read by picking the style that fits best.
Syntax
Ruby
if condition # code to run if condition is true elsif another_condition # code for another condition else # code if none of the above end # or using case case variable when value1 # code for value1 when value2 # code for value2 else # default code end # or using loops like while while condition # repeated code end
Ruby's control flow keywords include if, elsif, else, case, when, while, and until.
You can write some control flow in one line for simple checks, making code shorter and cleaner.
Examples
Basic if-else to check if a score is passing or failing.
Ruby
if score >= 60 puts "Pass" else puts "Fail" end
Using case to handle different days with clear options.
Ruby
case day when "Monday" puts "Start of week" when "Friday" puts "Almost weekend" else puts "Just another day" end
One-line if statement to print "Good" only if happy is true.
Ruby
puts "Good" if happy
Loop that repeats until count reaches 5.
Ruby
while count < 5 puts count count += 1 end
Sample Program
This program shows two ways to control flow: if-elsif-else to check a numeric score, and case to respond to letter grades.
Ruby
score = 75 if score >= 90 puts "Excellent" elsif score >= 60 puts "Good" else puts "Needs Improvement" end # Using case grade = 'B' case grade when 'A' puts "Top grade" when 'B' puts "Nice job" else puts "Keep trying" end
OutputSuccess
Important Notes
Ruby's multiple control flow styles let you pick the clearest way to express your logic.
Using the right style can make your code easier to read and maintain.
One-line control flow is great for simple checks but avoid it for complex logic to keep clarity.
Summary
Ruby has many control flow styles to fit different coding needs.
Use if for simple true/false decisions and case for multiple choices.
Loops like while help repeat actions until a condition changes.