Skip to content

Instantly share code, notes, and snippets.

@jim-clark
Last active July 2, 2018 12:44
Show Gist options
  • Save jim-clark/6027631efafdd1f316be to your computer and use it in GitHub Desktop.
Save jim-clark/6027631efafdd1f316be to your computer and use it in GitHub Desktop.

Click here to view as a presentation


Control Flow in Ruby


Learning Objectives


  • Identify the three main types of Control Flow

  • Use if & unless to perform branching

  • Use while & until to perform looping


Roadmap

  • Control Flow Review (5 mins)

  • Setup (5 mins)

  • Boolean Logic - Review (5 mins)

  • Branching Statements (15 mins)

  • Looping Statements (15 mins)

  • Other Useful Operators (5 mins)

  • Closing Questions (5 mins)

  • Practice Exercises (20 mins)


Control Flow Review (5 mins)


"The execution sequence of instructions in a program determined at run time with the use of control structures"

  • The Good News: Thanks to the JS knowledge you've acquired, you already have a nice grounding in the programming concepts of conditional expressions and control flow.

  • The Bad News: There are more options in Ruby, and thus more to learn. However, the basics will suffice and serve you well.


### Control Flow
Three Primary Types
  • Sequence:
    • Statements executed one at a time in sequence.

       car = Car.new
       car.start
       car.drive
  • Branching (selection):
    • if & unless Statements
  • Looping (iterative):
    • while & until Loops
    • each, times, for, etc., Iterating Methods

Setup (5 mins)


  • We won't write much code during this lesson, however, to complete the exercises, you will write code in a Ruby (.rb) file and run it in Terminal.

  • In your daily working directory:

     $ touch cf.rb
    
  • Then open in your code editor.


Setup


  • Type a bit of Ruby inside cf.rb and save it:

     puts "Hello WDI"
  • Run cf.rb in Terminal:

     $ ruby cf.rb
     > Hello WDI
    

Boolean Logic - Review (5 mins)


  • True/Truthy & False/Falsey

  • Comparison Expressions


Boolean Logic
True/Truthy & False/Falsey


  • Everything in Ruby is considered to be truthy except for ________ and ________.

  • As compared to JS, there are a couple of values that have different truthiness. What are they?


Boolean Logic
Comparison Operators


  • These Comparison Operators work exactly like they do in JS:

    • ==
    • !=
    • <
    • >
    • <=
    • >=
  • So do these logical combinators:

    • ||
    • &&

Boolean Logic
Comparison Operators

  • Here's an Operator we don't have in JavaScript, the Spaceship Operator:

    • <=>

       > 5 <=> 10
       => -1
      
  • The Spaceship Operator is unique in that it returns one of three values:

    • -1 if the expression on the left is less than the expression on the right.
    • 1 if the expression on the left is greater than the expression on the right.
    • 0 if the expressions are equal.

Branching Statements (15 mins)


  • Branching in Ruby is similar to that in JS, but with a few more options.

  • In this lesson, we'll touch upon these:

    • if statement

    • unless statement


Branching Statements
if (single path)

  • Single path if:                

     if val == 1
       puts "is one"
     end
  • Parens surrounding the logical expression are optional.


Branching Statements
if (inline conditional)

  • Remember, when possible, Ruby tries to read like English.

  • If you have a single path if, the following code

     if val == 1
       puts "is one"
     end

    can be written as

     puts "is one" if val == 1

Branching Statements
unless

  • Speaking of reading like English, the unless statement is designed to do just that. Think of it as the opposite of if.

  • For example, if you don't like using a not logical expression, you can use unless to remove the not logic:

     if val != 1
       puts "is not one"
     end

    can be written as

     unless val == 1
     	puts "is not one"
     end
  • You can also use unless inline just like with if. Like many things in Ruby, it's a matter of preference.


Branching Statements
if (dual path)


  • Dual paths if with else:

     if val == 1
     	puts "is one"
     else
     	puts "not one"
     end
  • then is optional unless you want to write an entire if statement on one line:

     if val == 1 then puts "is one" else puts "not one" end

Branching Statements
if (three or more paths)


  • Three or more paths if with elsif and optionally else:

     if val == 1
     	puts "is one"
     elsif val == 2
     	puts "is two"
     elsif val == 3
     	puts "is three"
     else
     	puts "not one, two, or three"
     end
  • That's not a typo, it's actually spelled as elsif!


Branching Statements
if is an expression


  • Unlike in JavaScript, the if statement is actually an expression and can be used to return a value. For example:

     # set the message variable to the appropriate string
     message = if val == 1
     	"is one"
     elsif val == 2
     	"is two"
     elsif val == 3
     	"is three"
     else
     	"not one, two, or three"
     end

Question - Branching Statements


Discuss the following with your pair and be prepared to share your code:

  • How could we write an if statement, on one line, that puts the text "Congrats!" if a variable named correct equals true?

Looping Statements (15 mins)


  • Again, lots of options. We'll just look at these:

    • while

    • until


Looping Statements
while

  • The first looping statement we'll look at is while:

     word = ""
     words = []
     while word != "end"
       print "Enter a word ('end' to quit): "
       word = gets.chomp
       words.push(word) if word != "end"
       puts "You've entered: #{words}"
     end
  • Use while when you want to continue to execute a block of code while a condition is true.

  • Beware of infinite loops!


Looping Statements
until

  • The next looping statement we'll look at is until:

     word = ""
     words = []
     until word == "end"
       print "Enter a word ('end' to quit): "
       word = gets.chomp
       words.push(word) if word != "end"
       puts "You've entered: #{words}"
     end
  • until works like a mirror image of while - it continues to execute a block of code until a condition is true.

  • Again, beware of infinite loops!


Looping Statements
modified while/until

  • You can also put the while/until condition at the bottom of the code block as follows:

     words = []
     begin
       print "Enter a word ('end' to quit): "
       word = gets.chomp
       words.push(word) if word != "end"
       puts "You've entered: #{words}"
     end until word == "end"
  • This approach guarantees that the code block will be executed at least once.

  • Notice also with this construct that there's no longer a need to initialize the word variable to prevent an error from occurring.


Looping Statements
for loop


  • Where's my for loop you ask?

  • Ruby does have a for loop, but it isn't much like that of JavaScript's, nor as commonly used.

  • It operates more like an each method.

  • Learning it's specifics is left up to you.


Question - Looping Statements


  • When using a while or until loop, we must be careful not put the program's execution into an __________ loop.

  • How do we avoid the above scenario?


Other Useful Operators (5 mins)


  • ||= (or equals operator)

  • Ternary Operator:
       <condition> ? <exp-if-true> : <exp-if-false>


### Other Useful Operators
or equals
  • The or equals operator is used to assign a value to a variable if it currently has no value, or is equal to either nil or false.

  • What will name equal after this code runs?

     name = "Fred"
     name ||= 25
  • After this code runs?

     name = false
     name ||= "Cool"
  • After this code runs?

     # assume name has never been used...
     name ||= false

Other Useful Operators
ternary

  • Our useful friend, the ternary operator works just like it does in JavaScript.

  • Just in case you forgot, it's ideal when you need to return one of two values depending upon a condition:

     message = score > 100 ? "You rock!" : "Keep trying!"
  • It can also be used to evaluate one of two expressions, so you can even run a method if you'd like:

     score > 100 ? game.winner : game.loop

Closing Questions (5 mins)

I'll give you a couple of minutes to review the following questions, meanwhile, I'll warm up the picker :)

  • In your own words, how would you describe Control Flow?

  • The three primary types of control flow are:
    1) Sequence
    2) ___________
    3) ___________

  • Why might you decide to use the modified version of the while/until loop, where the condition test is put at the end of the code block?


Practice Exercises (20 mins)


Practice Exercises

Exercise 1 - Branching

  • The following Ruby code will accept string input from the user, remove the automatic EOL character with chomp and store the string in a variable named choice:

     print "Enter a, b or c: "
     choice = gets.chomp
  • Write an if statement that puts the following messages:

    • a entered - "a is for apple"
    • b entered - "b is for banana"
    • c entered - "c is for cantaloupe"
    • anything else - "you're a rebel"

Practice Exercises

Exercise 2 - Looping


  • Use one of the looping statements to continue to execute the code you wrote in the previous exercise until no more fruit is entered by the user.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment