Learn about the conditional statement in Ruby.
The most commonly used conditional statement in Ruby is the if
statement. It contains a conditional expression and a true branch, and it may contain a false branch. The true branch is executed when the conditional expression is true. The false branch, if present, is executed when the conditional expression is false. The following program demonstrates the use of the conditional statement.
We want to write a program that determines eligibility for a driver’s license based on the age
input by the user. The eligible age should be or above.
print("Enter your age: ") age = Integer(gets) # Taking age input if age >= 18 # If age is greater than and equal to 18 print("You are eligible for a driver's license.\n") else print("You are not eligible for a driver's license.\n") end
The conditional statement used in the program above starts with if
, followed by a conditional expression. Line 4 contains the code to be executed if the condition is true. Note the indentation (extra space) at the start of line 4. The word else
on line 5 indicates the end of the true branch and the start of the false branch. Line 6 is the code that will be executed if ...