Last active
August 29, 2015 14:00
-
-
Save MilanGrubnic70/11089505 to your computer and use it in GitHub Desktop.
Control Flow: if, elsif, else, unless...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# if/elsif/else: | |
if expression | |
# Do something. Otherwise do nothing and got to next section of code. | |
end | |
if expression | |
# Do something | |
else | |
# Do yet another thing. Default response. | |
end | |
if expression | |
# Do something | |
elsif expression | |
# Do something else | |
else | |
# Do yet another thing. Default response. | |
end | |
################################################################################################## | |
# unless: | |
# Sometimes you want to use control flow to check if something is false, rather than if it's true. | |
# Ruby will let you use an unless statement. | |
# Basically a short hand if statement. It will do whatever you ask unless the condition is true. | |
# unless syntax looks like this: | |
unless condition | |
# Do something! | |
end | |
# For unless, the "# Do something!" bit will execute if the condition evaluates to false. | |
hungry = false | |
unless hungry # Looks to see if expression is false. | |
puts "I'm writing Ruby programs!" # It does this if false. | |
else | |
puts "Time to eat!" # It does this if true. | |
end | |
#=> "I'm writing Ruby programs!" | |
power_on = true | |
unless power_on | |
puts "Start the car." | |
else | |
puts "Turn off the car." | |
end | |
#=> "Turn off the car." | |
problem = false | |
print "Good to go!" unless problem | |
#=> "Good to go!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment