Git Product home page Git Product logo

conditional-readme's Introduction

Control Flow

Objectives

  • Define control flow for when a Ruby program is executed.
  • Implement control flow in different ways.
  • Use if, else, and elsif statements.

Define Control Flow

A control flow construct is a language feature which disrupts the normal progression to the next statement and conditionally or unconditionally branches to another location in source code. — Robert Klemme

In other words, control flow lets you tell your program what code to execute conditionally. As humans, we actually enact flow control every day. For instance, if you are hungry, you will go and get a snack. Otherwise, you'll stay put and continue to read this awesome readme.

Control flow is an important part of Ruby programming and web development. In the context of a web application, for example, you can easily think of content or functionality on a website you've visited that is only available to a user if that user is logged in.

Implementing Control Flow

There are several ways to tell your program to conditionally execute certain code, the basic forms of which are:

  • if, else, and elsif statements,
  • case statements,
  • loops.

In this reading, we're going to discuss the first group of these "conditional" statements: if, else, and elsif.

Use IRB, copying the provided code snippets, to follow along in this lesson.

if Statements

One of the most common ways to enact control flow is the if statement. Whatever block of code that follows the if statement will get evaluated — i.e. read and enacted by the computer. If this evaluation of the if statement results in true, then the code through to the associated end statement will run.

Let's look at a few examples:

if 5 > 2
  print "5 is greater than 2"
end
  • The code above will print "5 is greater than 2" because the if statement evaluates as true.

Meanwhile:

if 2 > 5
  puts "2 is greater than 5"
end
  • The code above will not print anything because the if statement evaluates as false.

So what if we want our program to print something else when the if condition evaluates as false?

The else Keyword

To accomplish this, we can follow an if statement with an else statement. Take a look:

if false
   puts "This will never get printed because the above
     statement evaluates to false."
else
   puts "This will get printed!"
end

An else statement sets a "default" condition for when your if statement's conditional evaluates as false. Every condition that doesn't evaluate as true will instead pass through the else statement.

Further Examples

So far, we've seen if statements that rely on the explicit use of the true and false booleans. Let's look at some examples that require a little more thought.

Example 1
if 6 + 3 == 9
  puts "Giraffes have no vocal cords."
end
#=> "Giraffes have no vocal cords."
  • The code above will print Giraffes have no vocal cords. Since 6 + 3 equals 9 (i.e. 9 is equal to 9), the if statement's conditional evaluates as true.

Top-tip: Remember that the comparative operator == ("double-equals") is used to check equality. This is distinct from the assignment operator = ("single-equals"), which is used to set the value of a variable.

Example 2
if 6 + 3 < 5
  puts "The hummingbird is the only animal that can fly backwards"
end
  • The code above will not print anything because 6 + 3, which is equivalent to 9, is not less than 5, making the if statement's conditional evaluate as false.
Example 3
dog = "satisfied"

if dog == "hungry"
  puts "Refilling food bowl."
else
  puts "Reading newspaper."
end

#=> "Reading newspaper."

elsif Statements

Sometimes, we want to control the flow of our program based on more than one condition. For example, if I am hungry, then I will get a snack. If I am thirsty, then I will get a drink of water. Otherwise, I will stay here and continue learning more about control flow.

We can add additional layers of complexity to our if and else statements by using the elsif keyword.

Let's add an elsif statement to Example 3 from above:

dog = "thirsty"

if dog == "hungry"
  puts "Refilling food bowl."
elsif dog == "thirsty"
  puts "Refilling water bowl."
else
  puts "Reading newspaper."
end

#=> "Refilling water bowl."

We can cascade as many elsif statements as we wish, however elsif statements can only be used following an if statement, and must precede the associated else statement (if used).

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

#=> "Snuggling."

Conclusion

In this lesson, we learned how to use control flow to execute code conditionally. Specifically, we learned:

  • how to use an if statement to execute code only if a certain condition is true

  • we can optionally use one or more elsif statements if we need to check multiple conditions and execute different code for each of them

  • we can optionally use an else statement if we want to specify "default" code that should execute if the condition(s) we are checking all evaluate as false

  • the order of the statements must be: if first, followed by any elsifs, and else, if used, last

That's all for now — we'll discuss case statements and looping in upcoming lessons.

conditional-readme's People

Contributors

aemrich avatar annjohn avatar aviflombaum avatar deniznida avatar dfenjves avatar eaud avatar fislabstest avatar fs-lms-test-bot avatar ihollander avatar kthffmn avatar lizbur10 avatar markedwardmurray avatar maxwellbenton avatar preetness avatar sarogers avatar sophiedebenedetto avatar

Stargazers

 avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

conditional-readme's Issues

needs stronger readme

needs to be fleshed out a bit:

if, else, elseif, unless statements

follow up with quiz or easier lab that grandma one?

if statements lab

Hello! I have been stuck in this lab for quite some time. Below is the code I submitted;

input_phrase = "I LOVE YOU GRANDMA!"

def speak_to_grandma(phrase)
if phrase == phrase.upcase
return "I LOVE YOU TOO PUMPKIN!"
end

The error states:
NoMethodError:
undefined method speak_to_grandma' for #<RSpec::ExampleGroups::SpeakToGrandma:0x00000 00000f49458> # ./spec/grandma_spec.rb:3:in block (2 levels) in <top (required)>'

Thank you

if true examples are contrived

I don't love using "if true" and "if false" as the initial examples, because they don't really give a good sense of what conditionals are used for. "true always evaluates to true" is not super intuitive or informative to beginners.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.