How to write case statement in Ruby?

In Ruby, Use ‘case‘ keyword instead of ‘switch‘ and ‘when‘ instead of ‘case‘. The case statement matches one statement with multiple conditions just like a switch statement in other languages.


case expression  
[when expression [, expression ...] [then]  
   code ]...  
   code ]  

Let’s understand, With Example:

print "Enter your day: "   
day = gets.chomp   
case day   
when "Tuesday"   
  puts 'Wear Red or Orange'   
when "Wednesday"   
  puts 'Wear Green'   
when "Thursday"   
  puts 'Wear Yellow'   
 when "Friday"   
  puts 'Wear White'   
 when "Saturday"   
  puts 'Wear Black'   
  puts "Wear Any color"   


Enter your day: Tuesday
Wear Red or Orange

Hope you understand how to write case statement program 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.