Control Flow

Case Statement in Ruby

Used to test variable equality for a list of values, where each value is a case. When the variable is equal to one of the cases, the statements following the case are executed. A break statement ends the switch case. The optional default case is for when the variable does not equal any of the cases.


Syntax
case variable
when value1
    #code to execute when variable is equal to value1
when value2
    #code to execute when variable is equal to value2
when value3..value4
    #code to execute when variable is in range of value3 and value4
else
    #default code to execute if none of the above values are reached
end

Notes

As seen above, ranges can be used in a case statement.


Example
puts "You're trying to escape an enemy spaceship. Will you choose the left or right door?"

door = gets.chomp

case door
when 'left'
    puts "You have reached the escape pod."
when 'right'
    puts "You broke the air-tight seal and you shot off into space."
else
    puts "The troopers have found you. You are under arrest."
end

Add to Slack

< If Statement   |   For Loop >

© 2019 SyntaxDB. All Rights Reserved.