Sunday, May 19, 2013

Ruby Lesson 2 Section 1: Introduction to Control Flow

Section Topics 

  • Control Flow
  • expression / if 
  • else
  • elsif
  • unless
Control Flow gives us flexibility in the repsonse Ruby will return. Think about it like a do it yourself fantasy book where you given a story and choices. The story will change depending on the choices you  make. This is the same with control flow, Ruby will return a designated response (choosing which block of code to run) depending on the user input.

Expression - Something that has value. This can be "true or false", a number, or something you set a variable to like the name David or a type of pet. 

if statements take an expression and runs a block of code if that expression is true, if it is not then it skips that block and moves onto the next block if there is one. You also need to add an end after an if block so Ruby will know that it has ended. 

  1. Input: if 5>4
                print "I'm greater than 4"

    Output: I'm greater than 4
  2. Input:if 5<4
                print "I'm greater than 4"

    Output: (nothing to print)

*Note: notice that the print command is intented. It is convention that we ident with 2 spaces after an if statement. 

else and elsif have the similar functions, think of them as a contingency plan if the if statement isn't true. Ruby will skip the if statement when false and go onto an else or elsif. The difference between the two is that else is always the last alternative options. You can have multiple elsifs, but only one else

  1. Input: x = 4

              if x>4
                print "I'm greater than 4"
              elsif x<4
                print "I'm less than 4"
                print "I'm equal to 4"

    Output: I'm equal to 4

Notice that I didn't input "else x=4". While this is an option and the Ruby wil have the same output it was unecessary as it was the only other possibility. 

unless statements checks for false statements. To me are just like if/else statements, seems pretty redundant to me. 

  1. Input: sick=false

               unless sick
                 puts "Going to school."
                 puts "Staying in bed, definitely not cause there's a test today."

    Output: Going to school. 

As you can see this can easily be done with an if/else statement, it's just another way to write it. 

No comments:

Post a Comment