Conditionals
Conditionals control the flow of execution of your program based on conditions that you define. Conditionals are the decision-making statements in your program.
If Statements
Decides if a block of code will be executed or not based on whether a condition is true.
age = 17if (age >= 16)puts "You are eligible to get your driver's license."end# Output: You are eligible to get your driver's license.
If - Else Statements
If the condition in an if statement is false, the block of code in the else statement will be executed.
age = 15if (age >= 16)puts "Can you drive me to the store?"elseputs "Can you walk with me to the store?"end# Output: Can you walk with me to the store?
If - Elseif - Else Statements
If the if
statement is not true, the block of code in the elseif
statement will be executed if the condition is true. There may me multiple elseif
statements. Finally, if none of the conditions are true, the block of code in the else
statement will be executed.
age1 = 35age2 = 26age3 = 19age4 = 17age5 = 15def things_you_can_do(age)if (age >= 35)puts "You can run for president."elsif (age >= 25)puts "You can rent a car."elsif (age >= 18)puts "You can vote."elsif (age >= 16)puts "You can get a driver's license."elseputs "You still have your youth!"endendthings_you_can_do age1things_you_can_do age2things_you_can_do age3things_you_can_do age4things_you_can_do age5# Output: You can run for president.# Output: You can rent a car.# Output: You can vote.# Output: You can get a driver's license.# Output: You still have your youth!
Ternary Statements
A shorter version of the if statement. It will evaluate an expression, if true, it will execute the code following the ?
. If false, execute the code following the :
.
# Example of condition evaluating to trueage1 = 19can_vote = (age1 >= 18) ? "You can vote." : "You can't vote."puts can_vote# Output: You can vote.# Example of condition evaluating to falseage2 = 17can_vote = (age2 >= 18) ? "You can vote." : "You can't vote."puts can_vote# Output: You can't vote.
All contributors
- christian.dinh2476 total contributions
- Anonymous contributorAnonymous contributor3071 total contributions
- robgmerrill124 total contributions
- christian.dinh
- Anonymous contributor
- robgmerrill
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.