Logic & Conditionals Flashcards
dog = “satisfied”
if dog == "hungry" puts "Refilling food bowl." else puts "Reading newspaper." end
What will happen?
puts “Reading newspaper.”
dog = “thirsty”
if dog == "hungry" puts "Refilling food bowl." elsif dog == "thirsty" puts "Refilling water bowl." else puts "Reading newspaper." end
What will happen?
puts “Refilling water bowl.”
dog = “cuddly”
if dog == "hungry" puts "Refilling food bowl." elsif dog == "thirsty" puts "Refilling water bowl." elsif dog == "playful" puts "Playing tug-of-war." elsif dog == "cuddly" puts "Snuggling." else puts "Reading newspaper." end
What will happen?
puts “Snuggling.”
How do we write the following as a ternary operator?
age = 1 if age < 2 "baby" else "not a baby" end
age = 1
age < 2 ? “baby” : “not a baby”
What is the basic structure of a ternary operator?
conditional ? action_if_true : action_if_false
What would an if statement modifier look like?
this_year = 2020
puts “Hey, it’s 2016!” if this_year == 2016
What would an unless statement modifier look like?
this_year = 2020
puts “Hey, it’s not 2016!” unless this_year == 2016
True or False: The following if statement would be a good candidate for using a ternary operator instead.
if condition_a something else something_else end
True
How do we turn the following if statement into a ternary operator?
if condition_a something else something_else end
condition_a ? something : something_else
What will happen in the following code?
name = “Steven”
puts “Hi, #{name}” if name == “Steven”
puts “Hi, Steven”
What will happen in the following code?
name = “Steven”
puts “Hi, #{name}” unless name == “Steven”
Nothing
When is it good to use a case statement instead of an if statement?
It’s good to use a case statement when you have a lot of if and elsif statements to check the value of one variable.
How would the following if/elsif statement look like as a case statement?
name = “Alice”
if name == "Alice" puts "Hello, Alice!" elsif name == "The White Rabbit" puts "Don't be late, White Rabbit" elsif name == "The Mad Hatter" puts "Welcome to the tea party, Mad Hatter" elsif name == "The Queen of Hearts" puts "Please don't chop off my head!" else puts "Whoooo are you?" end
case name
when "Alice" puts "Hello, Alice!" when "The White Rabbit" puts "Don't be late, White Rabbit" when "The Mad Hatter" puts "Welcome to the tea party, Mad Hatter" when "The Queen of Hearts" puts "Please don't chop off my head!" else puts "Whoooo are you?" end
What will happen in the following code?
greeting = “friendly_greeting”
case greeting when "unfriendly_greeting" puts "What do you want!?" when "friendly_greeting" puts "Hi! How are you?" end
puts “Hi! How are you?”
What will happen in the following code?
current_weather = “raining”
case current_weather when "sunny" puts "grab some sunscreen!" when "raining" puts "grab an umbrella" when "snowing" puts "bundle up" end
puts “grab an umbrella”