The case statement in Ruby is used to implement multiway branching, where the program selects one of several alternatives based on the value of an expression. Here are a few examples of how to use the case statement in Ruby:
.jpg)
Example 1: Checking for Grades
print "Enter your grade: " grade = gets.chomp.upcase case grade when "A" puts "Excellent!" when "B" puts "Good job!" when "C" puts "Needs improvement." when "D", "F" puts "Sorry, you failed." else puts "Invalid grade." end
In this example, the user is prompted to enter their grade. The program then uses the case statement to check the value of the grade variable. If the value is "A", the program prints "Excellent!". If the value is "B", the program prints "Good job!". If the value is "C", the program prints "Needs improvement.". If the value is "D" or "F", the program prints "Sorry, you failed.". If the value is anything else, the program prints "Invalid grade.".
Example 2: Checking for Days of the Week
print "Enter a day of the week: " day = gets.chomp.downcase case day when "monday", "tuesday", "wednesday", "thursday", "friday" puts "It's a weekday." when "saturday", "sunday" puts "It's a weekend." else puts "Invalid day." end
In this example, the user is prompted to enter a day of the week. The program then uses the case statement to check the value of the day variable. If the value is one of the weekdays ("monday", "tuesday", "wednesday", "thursday", "friday"), the program prints "It's a weekday.". If the value is one of the weekend days ("saturday", "sunday"), the program prints "It's a weekend.". If the value is anything else, the program prints "Invalid day.".
Example 3: Checking for Ranges of Numbers
print "Enter a number: " number = gets.chomp.to_i case number when 0..9 puts "Single digit number." when 10..99 puts "Double digit number." when 100..999 puts "Triple digit number." else puts "Number is too large." end
In this example, the user is prompted to enter a number. The program then uses the case statement to check the value of the number variable. If the value is between 0 and 9, the program prints "Single digit number.". If the value is between 10 and 99, the program prints "Double digit number.". If the value is between 100 and 999, the program prints "Triple digit number.". If the value is anything else, the program prints "Number is too large.".
1 Comments
Great examples
ReplyDelete