Open In App

Ruby | Case Statement

The case statement is a multiway branch statement just like a switch statement in other languages. It provides an easy way to forward execution to different parts of code based on the value of the expression.

There are 3 important keywords which are used in the case statement:



Syntax:

case expression

when expression 1
  # your code

when expression 2
  # your code
.
.

else
  # your code
end

Flow Chart:



Example 1:




# Ruby program to illustrate the 
# concept of case statement
  
#!/usr/bin/ruby   
  
print "Input from one, two, three, four: "  
  
# taking input from user
# str = gets.chomp
  
# hardcoded input
str = "two"
  
# using case statement
case str 
  
# using when
when "one"  
  puts 'Input is 1'
  
when "two"  
  puts 'Input is 2'
  
when "three"  
  puts 'Input is 3'
  
 when "four"  
  puts 'Input is 4'
  
else  
  puts "Default!"
  
end  

Output:

Input from one, two, three, four: Input is 2

Example 2:




# Ruby program to illustrate
# case statement
  
#!/usr/bin/ruby
  
marks = 70
  
# marks is the input
# for case statement
case marks
  
# using range operators ..
when 0..32
  puts "You fail!"
  
when 33..40
  puts "You got C grade!"
  
when 41..60
  puts "You got B grade!"
  
else
 puts  "You got A grade!"
   
end

Output:

You got A grade!

Important Points:


Article Tags :