Skip to content

Instantly share code, notes, and snippets.

@stacietaylorcima
Last active January 8, 2018 23:01
Show Gist options
  • Save stacietaylorcima/e7310f32cd260cbf7093e2c7eda6134e to your computer and use it in GitHub Desktop.
Save stacietaylorcima/e7310f32cd260cbf7093e2c7eda6134e to your computer and use it in GitHub Desktop.
Give your programs the ability to make decisions by using control structures.

Ruby: Conditionals & Logic

Objectives

  • Apply conditional expressions and logic operators.
  • Demonstrate how to use short circuit evaluation.
  • Apply comparator operators to establish order relationships between the objects.
Concept Description
if It begins a conditional statement and evaluates an expression; it must be 'ended' with an end
elsif An optional branch that allows you to check for additional conditions
else An optional branch in a conditional statement. It executes when no other condition is met
Ternary operator Provides a shorthand syntax for conditional statements with only two possible outcomes. condition ? do_this : do_that which reads as "if the condition evaluates as true, then do this, else, do that"
unless Unless is the inverse of if. It executes the branch unless the condition evaluates as true
case Case is another way to format the control structure. It evaluates an expression and provides direction by matching the result using when to different possibilities
&&, and A binary logic operator that evaluates two expressions. It evaluates to true if both expressions evaluate to true themselves
or A binary logic operator that evaluates two expressions. It evaluates to true if either one of the expressions evaluate to true
!, not A unary logic operator that evaluates one expression and negates its value
truthy Something that evaluates as true. Everything in Ruby is truthy except nil and false
falsey Something that evaluates as false, such as nil or false

Conditionals

When we need a program to make a decision, we use a conditional statement. Conditional statements will evaluate an expression and perform an action based on the result.

  • Your program will visit the conditional branches in order from the top to the bottom. If the condition of the current branch evaluates as true, it runs the block of code inside that branch, and then it exits the conditional statement, so no other branches get visited.

if Statement

  • The if in the first line tells Ruby that we are about to use a conditional statement

  • Whatever comes after it, the condition, is an expression that needs to be evaluated.

  • If that expression is evaluated as true, the line with the comment gets executed.

  • All if statements need to be "ended" with an end just like our method definitions.

  • Write a condition that says if it's a weekday, we want to take the quick path home (which angles to the left):

its_a_weekday = true

if its_a_weekday
  "We're going to the left!"
end
  • In the case above, its_a_weekday is the expression that our conditional statement needs to evaluate.
  • When it is evaluated, it returns true because that's the value stored in the variable.
  • Because the condition is evaluated as true, the block in that branch of the conditional statement executes and returns "We're going left!".

if/else Statement

  • There's a problem, though. What should the program do if it's not a weekday and we don't want to go left?
  • Give the program the ability to make a decision in the case the its_a_weekday evaluates to false
  • You do this by using an optional else branch in our conditional statement.
its_a_weekday = false

if its_a_weekday
  "We're going left!"
else
  "We're going right!"
end

Conditional Return

Use a conditional return to set the value of a variable based on an expression.

its_a_weekday = false

direction = if its_a_weekday
  "We're going left!"
else
  "We're going right!"
end

p direction #=> "We're going right!"

elsif Statement

  • Notice spelling of elsif
  • What if there are more than 2 possibilities? In that case we can evaluate any number of conditionals by using elsif branches.
  • Add a variable to hold a Boolean value that tells us if it's the weekend:
its_a_weekday = false
its_the_weekend = true

if its_a_weekday
  "We're going left!"
elsif its_the_weekend
  "We're going right!"
end
  • elsif will evaluate the condition just like an if branch will.
  • It will only execute it's block of code if the condition evaluates as true.
  • Notice that there is no else branch in the example above.
  • It's optional. The else branch does not need an expression to evaluate since it should execute if no conditions above it evaluate as true.
its_a_weekday = false
its_the_weekend = false

if its_a_weekday
  "We're going left!"
elsif its_the_weekend
  "We're going right!"
else
  "Turn around! Something is weird!"
end

Inline if Statement

Have a long conditional statement? There are also some special cases that will let us use more concise syntax. The inline if statement allows you to execute something if a condition evaluates as true. Here is the recipe for an inline ‘if’ statement:

do_this if condition)
  • Notice that there is no end in this statement. The condition is evaluated and the code to the left of the if keyword is executed if the condition evaluates as true.
def weekend?
  its_the_weekend = true

  return "Time to go work on my tan!" if its_the_weekend
end
  • In Ruby, return statements can be used implicitly.
  • In this case, we used it explicitly because it improves the readability of this statement.
  • Also, if there was more code after this line and this conditional was inside of a method, it could return something other than what we intend it to. This is because methods in Ruby return the last thing they evaluate unless there is an explicit return statement present.

Conditionals using the Ternary Operator

  • Only have 2 possibilities in your conditional? Make the statement even shorter by using the ternary operator.
  • The ternary operator allows the program to evaluate a condition and return one thing if the statement evaluates to true, else it returns another thing.
  • Here's what the ternary operator looks like:
condition ? do_this : do_that
  • Read that as "if the condition is true, then do this. Else, do that."
day_of_the_week = "Sunday"

day_of_the_week == "Sunday" ? "Go back to sleep" : "Rise and shine!"

unless Statement

_Ruby also has an inverse of the of statement called the unless statement. It can be used inline as well as in standard form.

movie_is_over? = true

# inline
return "Grab the popcorn" unless movie_is_over?

# expanded
unless movie_is_over?
  "Grab the popcorn"
end

case Statement

Recall the very long day of the week conditional statement. Ruby can work through that type of situation when you want to check some input against multiple choices. The case statement looks like this:

case expression
  when expression_matches_this
    do_this
  when expression_matches_that
    do_that
  when expression_matches_this_here, or_this, or_that
    do_this_here_for_any
  else
    do_default
end
  • In this case, the expression is evaluated and then matched against any number of options.
  • Options can be separated with a comma to execute the same block of code for more than one possibility.
  • Let's refactor the day of the week conditional statement using a case statement:
weekday = "Saturday"

case weekday
    when "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
        "It's a weekday..."
    when "Saturday", "Sunday"
        "It's the weekend!"
    else
        "There is no spoon."
end

Logic Operators

The && Operator

The && operator, also called ‘with and, is a binary operator that will work on two expressions. It will return as true, if and only if, both expressions evaluate as true themselves.

going_out = true
its_raining = true

if going_out && its_raining
  "Take an umbrella."
end

The || Operator

The || operator, also called with or, is another binary operator that like the and operator, works with two expressions to return a new expression itself. In this case, if either of the two expressions being evaluated returns as true, the expression will return true.

hungry = true
bored = false

if bored || hungry
  "Raid the fridge"
end
  • We can also use the || operator in conjunction with the = operator to provide a value if nothing is provided initially.
  • In the case that current_activity is falsey, it will take on the value of favorite_activity.
current_activity = nil
favorite_activity = "Coding"

current_activity ||= favorite_activity

p current_activity # returns "Coding"

The ! Operator

The ! operator, also called with not, is a unary operator, meaning that it works with one expression, and allows us to negate the value of an expression. That is, if an expression evaluates as true, negation makes it false and if it evaluates as false, negation makes it true.


all_is_well = true

if !all_is_well # can also use not all_is_well
  "Have some cake"
end
  • The condition above reads if not all_is_well.
  • Using negation in an if statement condition produces the same result as if we used unless instead.

"Truthy" & "Falsey"

Truthy refers to things that evaluate as if they were true. In Ruby, everything that isn't nil or false will be truthy (be evaluated as true).


@stacietaylorcima
Copy link
Author

Exercises

password_checker

  • Define a method called password_checker with a parameter called password. The method should return "Password accepted!" if the argument passed for password is a String object between 6 and 10 characters long. It returns "Password declined!" if password does not meet that criteria.

Solution:

def password_checker(password)

  if password.length >= 6 && password.length <= 10
     return "Password accepted!"
  else
   "Password declined!"
  end 

end

And/Or

  • Define a method called lock. It should take four arguments:
def lock(a,b,c,d)
end
  • Each argument represents a number on a combination lock. The method will return "unlocked" or "locked" based on whether the combination is correct. There are several combinations that are "correct".
    • The first number has to be a 3, 5, or 7
    • The second number has to be a 2
    • The third number has to be a 5 or a 6
    • The fourth number has to be 8, 9 or 0
    • An example of satisfying the first number condition is:
if (a == 3 || a == 5 || a == 7)

Solution:

def lock(a,b,c,d)
  
  if (a == 3 || a == 5 || a == 7) && (b ==2) && (c == 5 || c == 6) && (d == 8 || d == 9 || d == 0)
    "unlocked"
  else
    "locked"
  end
  
end

can_i_get?

  • Define another method. This method is called can_i_get? and should take two arguments:
def can_i_get?(item,money)
end
  • The first argument represents what the user wants to buy.
    • According to the specs below, the user can buy a computer or an iPad.
  • The second argument represents how much money the user has. The method should evaluate if the user has enough money to buy a computer or an iPad. If the user has enough money for a computer or an iPad, the method should return true, otherwise it should return false. An example for the first condition is:
if item == "computer" && money >= 1000
  • Use elsif rather than separate if statements.

Solution:

def can_i_get?(item,money)
  if item == "computer" && money >= 1000
    true
  elsif item == "ipad" && money >= 500
    true
  else
   false
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment