How to write case statement in ruby?
A case
statement in Ruby is a control flow structure that allows us to compare a value against multiple conditions in a clean and readable way. It functions similarly to a switch
statement in other languages.
Syntax:
case variable
when condition1
# Code to execute if variable matches condition1
when condition2
# Code to execute if variable matches condition2
else
# Code to execute if no conditions match
end
Example:
puts "Enter 1 to order tea, 2 to order coffe and 3 to order milk:"
orderTypeNo = gets.chomp.to_i
case orderTypeNo
when 1
puts "Thanks for your order. We will serve your tea in 5 mins."
when 2
puts "Thanks for your order. We will serve your coffe in 10 mins."
when 3
puts "Thanks for your order. We will serve your milk in 3 mins."
else
puts "The Item you have ordered is not available write now."
end