Conditions
We use conditions to change the behaviour depending on one or multiple inputs
Before we can use if, we need to have something that is either true or false
3 > 2
true
"dog" == "dog"
true
2 > 2
false
"dog" == "cat"
false
"Ruby".include?("Rails")
false
This is how we use a condition in its simplest form:
weather = "rain"
if weather == "rain"
puts "It rains. Take an umbrella with you."
end
puts "Have a nice day!"
This is how we explicitly define the else case:
weather = "sunny"
if weather == "rain"
puts "It rains. Take an umbrella with you."
else
puts "It does not rain. You can leave the umbrella at home."
end
puts "Have a nice day!"
This is how we add more conditions using elsif:
weather = "sunny"
if weather == "rain"
puts "It rains. Take an umbrella with you."
elsif weather == "sunny"
puts "It's sunny. Awesome!"
else
puts "It's not raining nor is it sunny."
end
puts "Have a nice day!"
# bad
if weather = "rain"
puts "It rains."
else
puts "It does not rain" # This is never executed
end
# good
if weather == "rain"
puts "It rains."
else
puts "It does not rain"
end
# bad
if weather == "rain"
puts "It rains."
puts "Have a nice day!"
# good
if weather == "rain"
puts "It rains."
end
puts "Have a nice day!"
# bad
if weather == "rain"
puts "It rains."
elseif weather == "sunny"
puts "It's sunny!"
end
# good
if weather == "rain"
puts "It rains."
elsif weather == "sunny"
puts "It's sunny!"
end
# bad
if weather == "rain"
puts "It rains."
elsif weather == "sunny"
puts "It's sunny!"
else
puts "Neither rain nor sun"
end
# good
if weather == "rain"
puts "It rains."
elsif weather == "sunny"
puts "It's sunny!"
else
puts "No rain, no sun"
end
if condition1
# this part is executed if condition1 was true
elsif condition2
# this part is executed if condition1 was false,
# but condition2 was true
# there can be as many elsif's as needed
else
# this part is executed if condition1 AND
# condition2 were false
end
What questions do you have?