Ruby Monstas


Conditions

Conditions

We use conditions to change the behaviour depending on one or multiple inputs

  • If it rains, take an umbrella with you
  • If you're hungry, eat an apple
  • If the payment was successful, send a mail

true or false

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

Example "if"

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!"

Example "if-else"

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!"

Example "if-elsif-else"

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!"

Common mistakes

  • Confusion btw assignment (=) and comparison (==)
  • Not providing the end key word
  • elsif (not elseif or else if)
  • Not using indentation for visual orientation
(each case is described below)

Assignment (=) vs Comparison (==)

# 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

Forgetting the end keyword

# 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!"

elsif

# 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

indentation is our friend

# 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-Then-Else Summary

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
  • There is always one if and one end
  • Optionally there are as many elsif as required
  • Optionally there is one else

Additional Resources

Ruby For Beginners: Conditionals

What questions do you have?

Sources

Images