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:
- case: It is similar to the switch keyword in another programming languages. It takes the variables that will be used by when keyword.
- when: It is similar to the case keyword in another programming languages. It is used to match a single condition. There can be multiple when statements into a single case statement.
- else: It is similar to the default keyword in another programming languages. It is optional and will execute when nothing matches.
Syntax:
case expression
when expression 1
# your code
when expression 2
# your code
.
.
else
# your code
end
Flow Chart:

Example 1:
print "Input from one, two, three, four: "
str = "two"
case str
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:
marks = 70
case marks
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:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
26 Oct, 2018
Like Article
Save Article