Basics
Ruby If Else
Conditional Statements
Ruby if-else statements control flow with concise syntax.
Introduction to If-Else Statements
The if-else statement in Ruby is a fundamental control structure used for decision making. It executes code based on whether a condition evaluates to true or false. This allows developers to control the flow of their programs based on different conditions.
Basic Syntax of If-Else
The if
keyword is followed by a condition. If the condition is true, the block of code immediately following the condition is executed. Otherwise, the code following the else
keyword is executed. The statement is concluded with the end
keyword.
Example: Simple If-Else Usage
In the example above, the program checks if the age
variable is greater than or equal to 18. If true, it outputs "You are eligible to vote." Otherwise, it outputs "You are not eligible to vote."
Using Elsif for Multiple Conditions
The elsif
keyword allows you to check multiple conditions within an if-else statement. This is useful when you have more than two possible outcomes.
Here, the program first checks if number
is greater than 20. If not, it checks if the number is greater than 10. If neither condition is true, it executes the else
block.
One-Liner If-Else Statements
Ruby allows you to write if-else statements in a single line for simple conditions. This can make your code more concise.
The above example uses a ternary operator to achieve the same result as a multi-line if-else statement but in a more compact form.