Ruby Case Statement

In Ruby, we use ‘case’ 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.

Syntax:

  1. case expression  
  2. [when expression [, expression …] [then]  
  3.    code ]…  
  4. [else  
  5.    code ]  
  6. end  

Example:

  1. #!/usr/bin/ruby   
  2. print “Enter your day: ”   
  3. day = gets.chomp   
  4. case day   
  5. when “Tuesday”   
  6.   puts ‘Wear Red or Orange’   
  7. when “Wednesday”   
  8.   puts ‘Wear Green’   
  9. when “Thursday”   
  10.   puts ‘Wear Yellow’   
  11.  when “Friday”   
  12.   puts ‘Wear White’   
  13.  when “Saturday”   
  14.   puts ‘Wear Black’   
  15. else   
  16.   puts “Wear Any color”   
  17. end   

Output:

Ruby switch 1

Look at the above output, conditions are case sensitive. Hence, the output for ‘Saturday’ and ‘saturday’ are different.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *