Conditional Structures
Conditional structures provide you with a way of testing one or more variables to see if they meet a certain condition. This could be testing if they are equal to a certain value or are within a range of values. If the test succeeds, then a code block is executed. If the test fails, then a different code block is executed. Since there are many different times where you will want to do this, Crystal syntax provides you with a lot of options to match your circumstance. Each has its own benefits and drawbacks that you need to consider when deciding which to use. The conditional structures are the If statement and the Select Case statement.
The If statement tests a condition and performs one action if the condition is true and another action if it’s false. The code after the Then keyword is executed if the test succeeds. The code after the Else keyword is executed if the test returns false. Crystal syntax also supports the Else If statement.
Crystal syntax does not have an End If statement. It considers the entire If block a single statement. Put the line terminator after the Else block to terminate it. The Else If keyword is actually two words. If there is more than one statement within a code block then enclose the statements within parentheses and use the semicolon to terminate each statement.
Here are some actual examples using Crystal syntax.
When you have to compare a single value to multiple conditions, this can result in a lot of If statements nested within each other. Rather than next If statements, you can replace the entire If structure with a single Select Case statement. The Select Case statement lets you test a field against multiple conditions and execute a block of code when a condition matches. Each condition has a separate code block associated with it.
In Crystal syntax, the Select Case statement is built by first typing the keyword Select followed by the variable name you want to test. After that, you list each case block. A case block consists of the keyword Case followed by the condition to test and terminated with a colon. The next series of lines are the lines to execute if the condition matches. You can list multiple conditions for a single Case statement by separating each condition with a comma. If none of the Case statements are true, then the code in the Default block is executed. Finish a Case block with two semicolons. The following code block is a template for how to fill in a Select statement.
The next example demonstrates testing a value across a range of values
Note that the last line uses the Is operator in the condition. This is used when you want to use one of the comparison operators (>, <. >=, etc.)