Control Structures – case Statements in Ruby

Control Structures - case Statements in Ruby

As we have seen in the previous lessons, we can check for multiple conditions using the if/elsif/else expression.
A more simplified and flexible option is the case expression, which tests a value in when statements. You can have as many when statements as you need for a single case. Note that the case expression must be closed with the end keyword. case statements are used when you need to make different decisions based on a value.
For example:

Multiple values can be tested within a single when by separating the values with commas.
For example:

If you forget to put a comma between two values, Ruby will return a syntax error.

syntax error, unexpected tINTEGER, expecting keyword_then or ‘,’ or ‘;’ or ‘\n’

An else statement can be provided to execute code if no when condition matches.
For example:

Leave a Reply