Intro to Ruby

Class 2

Welcome Back!

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

Reminder! Some "rules":

  • We are here for you!
  • Every question is important.
  • Help each other.
  • Have fun!

Homework Discussion

How was last week's homework? Do you have any questions or concepts that you'd like to discuss?

Review

  • Arithmetic and variables
  • Data types

IRB

  • IRB ("interactive ruby") is a command line interface to Ruby that is installed when we install Ruby. It works like a calculator and is a great way to get started quickly. This is a lot like the Repl we used in Class 1.
  • Open: In your terminal, type `irb`
  • Quit: Type `quit` and then press `enter`
  • What we will cover today

    • Boolean Expressions and Conditionals
    • Loops
    • Collections

    Booleans

    A boolean is a data type. It can have only two values: true or false.

    Boolean Expressions

    Code that compares values and returns True or False is called a Boolean expression

    • Test for equality by using `==`. We can't use `=` because that is used for assignment
    • Test for greater than and less than using `>` and `<`

    Boolean Expressions cheat sheet

    a == b a is equal to b
    a != b a does not equal b
    a < b a is less than b
    a > b a is greater than b
    a <= b a is less than or equal to b
    a >= b a is greater than or equal to b

    Learn more about logical operators in Ruby here.

    Boolean Expressions practice

    
        # try some of these out in IRB
        first_num = 3
        second_num = 4
        first_num != second_num
        first_num <= 3
        first_num >= 4
    
        first_num = 5
        second_num = 5
        first_num == second_num
    
        # Combine comparison and assignment
        nums_are_equal = (first_num == second_num) 
        puts nums_are_equal
                    

    Remember: Equals does not equal "equals equals"

    Further reading on boolean expressions...

    Boolean Expressions

    A boolean expression evaluates to true or false. It can also have multiple parts, joined by AND (&&) or OR (||).

    EXPRESSION EVALUATES TO
    true && true true
    true && false false
    false && false false
    true || true true
    true || false true
    false || false false
    not (true && false) true

    Ruby operators and boolean expressions have precendence rules!

    Further practice on boolean expressions

    Let's Develop It

    Take a few minutes and experiment with boolean expressions in IRB. You can start with the examples below.

    
    true && false
    1 == 1 && 2 > 37
    "boop" == "bip" || 7 == 8
    false || true 
    89 > 88 || 89 < 90
    true || not(1 == 1 || 2 == 65)
                    

    Putting Booleans to Work

    So, what's the value of knowing if a statement is true or false? Often, you'll use that to control whether a piece of code will execute or not.

    Can you tell what this code does?

    
        print "Guess my secret number: "
        user_guess = gets.chomp.to_i
        secret_number = 312
    
        if user_guess < secret_number 
            puts "Too low!"
        elsif user_guess > secret_number
            puts "Too high!"
        else 
            puts "You guessed it! Wow, maybe you're psychic...."
        end 
                    

    Conditionals

    When we want different code to execute depending on certain criteria, we use a conditional

    We achieve this using if statements and boolean expressions.

    
        if number == 5
            puts 'number is equal to 5'
        end
                    

    Conditionals

    We often want a different block to execute if the statement is false. This can be accomplished using else.

    
        if number == 5
            puts 'number is equal to 5'
        else
            puts 'number is not equal to 5'
        end
                    

    Conditionals

    The following shows some examples of conditionals with more complex boolean expressions:

    
        # And
        if x > 3 && y > 3
            puts 'Both values are greater than 3'
        end
    
        # Or 
        if x != 0 || y != 0
            puts 'The point x,y is not on the x or y axis'
        end
    
        # Not
        if not(x > y)
            puts 'x is less than or equal to y'
        end
                    

    Chained conditionals

    Conditionals can also be chained.

    Chained conditionals use elsif to test if additional statements are true. The single 'else' action will only happen if all preceding conditions are false.

    For example:

    
        if number > 10
            puts "number is greater than 10"
        elsif number <= 10 && number > 0
            puts "number is a number between 1 and 10"
        else
            puts "Wow, don't be so negative!"
        end
                    

    Let's Develop It!

    
        # adventure.rb                   
        puts "A vicious dragon is chasing you!"
        puts "Your choices:"
        puts "1 - Hide in a cave"
        puts "2 - Climb a tree"
    
        user_choice = gets.chomp
    
        if user_choice == '1'
            puts "You hide in a cave. The dragon finds you and asks if you'd like to play Scrabble. Maybe it's not so vicious after all!"
        elsif user_choice == '2'
            puts "You climb a tree. The dragon can't find you."
        else 
            puts "That's not a valid option."
        end 
                    
    
        # run the file from your terminal
        ruby adventure.rb
                    

    Let's Develop It!

    Write a program in your text editor that uses conditionals and user input to allow the user to play an adventure game.

    "gets.chomp" is the value of user input at the command line, with the trailing whitespace chomped off. To do math with it, convert it to an integer with the ".to_i" method

    
        user_input = gets.chomp.to_i 
                    

    Run your program by calling it with Ruby from the command line.

    
        $ ruby program_name.rb 
                    

    Loops

    It is often useful to perform a task and to repeat the process until a certain point is reached.

    The repeated execution of a set of statements is called iteration, or, more commonly, a loop.

    One way to achieve this, is with the while loop.

    
        number = 10
    
        while number > 0
            puts "Loop number #{number}"
            number = number - 1
        end 
    
        puts 'Done!'
                    

    While Loops

    
        number = 10
    
        while number > 0
            puts "Loop number #{number}"
            number = number - 1
        end 
                    

    The while statement takes a condition, and as long as it evaluates to true, the code block beneath it is repeated. This creates a loop.

    Without the `number = number - 1` statement, to decrement the value of `number`, this would be an infinite loop :( :( :(

    While loops

    Consider the following example that uses a while loop to sing you a song.

    
            num_bottles = 99
    
            while num_bottles > 0
                puts "#{num_bottles} bottles of beer on the wall, 
                #{num_bottles} bottles of beer, take one down, pass it 
                around, #{num_bottles - 1} bottles of beer on the wall!"
    
                num_bottles = num_bottles - 1
            end 
                    

    "#{num_bottles}" is an example of string interpolation

    Let's Develop It

    • Write a program that obtains user input like the last program
    • This program should not exit until the user says it should (maybe by entering "quit"?)
    • Use a loop!
    • You can use the next slide as an example.

    Let's Develop It: Example

    
        # loopy.rb
        loopy = true
    
        while loopy == true
            puts "Are we having fun yet?"
            puts "Answer 'true' or 'false'."
            user_input = gets.chomp
            if user_input == 'false'
                loopy = false
            end 
        end 
                    

    Learn more about loops in Ruby here.

    Each loops

    The most commonly used type of loop in Ruby is an each loop. It uses the .each method to iterate over a collection of elements, doing work to each one.

    First, we need a collection. Let's use a range of numbers to loop over.

    
        (0..5).each do |num|
            puts "Value of num is #{num}"
        end
                    

    Each loops

    
        (0..5).each do |num|
            puts "Value of num is #{num}"
        end
                    

    The loop has three parts:

    The collection that will be looped through, in this case a range of "(0..5)"

    The name to give each element when the loop begins again - "num" - in the pipes "| |"

    The code to execute with the element - the puts statement

    We will revisit the each loop when we have a better understanding of collections.

    Collections

    There are three main types:

    • Ranges
    • Arrays
    • Hashes (we will get to these next time)
    
        new_range = (1..10)
    
        new_array = [1, 3, 5]
                    

    Ranges

    
        inclusive_range = (1..3)  # contains 1, 2, 3
        exclusive_range = (1...3) # contains 1, 2
        letter_range = ('a'..'e') # contains 'a', 'b', 'c', 'd', 'e'
                    

    Ranges are the range of values between the given first and last elements.

    Inclusive ranges have two dots, and include the last element.

    Exclusive ranges have three dots, and do not include the last element.

    Ranges must be defined from lowest value to highest.

    Ranges

    Try out these range methods in IRB.

    
        (1..99).max
        ('b'...'z').include?('j')
        (890..902).begin
        (890..902).first(4)
        (890..902).last(3)
        (890..902).end
        (22..28).min
    
        ('a'...'g').each do |letter|
            puts "#{letter} is a pretty good letter"
        end 
    
        (22..28).to_a
                    

    Arrays

    Arrays have square brackets and can be filled with any type of object: integers, floats, strings, even other arrays or hashes.

    
        num_array = [1, 3, 5, 89, 212, 7, -100]
        string_array = ["wow", "woooo", "zowie"]
        new_array = Array.new # will have no elements inside it initially
        varied_array = ["one", 2, "THREE", 0.4, ["five", 6]]
    
        # methods to get information about an array
        num_array.length
        string_array.include?("yee ha")
                    

    Arrays are a great way to keep track of information that changes frequently.

    Accessing Elements in an Arrays

    Arrays are ordered and are integer-indexed, starting at 0.

    Elements can be accessed by their position.

    
        num_array = [1, 3, 5, 89, 212, 7, -100]
        string_array = ["wow", "woooo", "zowie"]
    
        num_array[0]            # returns the zeroth element 
        string_array[2]         # returns the third element 
        string_array[-1]        # returns the last element
        num_array.last          # returns the last element 
        num_array[1..2]         # returns the second and third elements
        string_array.first      # returns the first element 
                    

    Adding & Deleting From Arrays

    Adding and removing items to an array can be done in a variety of ways. These are the most common.

    
        string_array = ["wow", "woooo", "zowie"]
    
        # add
        string_array.push("hot diggity") # adds argument as last element
        string_array << "yikes"          # adds argument as last element
    
        # remove
        string_array.delete("wow")       # deletes the element that matches argument
        string_array.pop                 # removes and returns the last element
        string_array.shift               # removes and returns the first element
                    

    More Array Methods

    Arrays are used a lot in Ruby. There are a lot of cool methods available for them.

    
        arr = ["dog", "cat", "turtle", "parakeet", "ferret"]
    
        arr.index("dog") # returns the index of the element that matches argument
        arr.join         # returns a string made up of all the elements
        arr.reverse      # returns new array with same elements, reversed
        arr.shuffle      # returns new array with same elements, shuffled
        arr.uniq         # returns a new array with only unique elements     
        arr.size         # returns the number of elements in the array
        arr.empty?       # returns a boolean 
        arr.clear        # removes all elements from the array
                    

    Learn more about arrays here.

    Homework

    The Ada Developers Academy Jumpstart Curriculum has two great assignments for practicing conditional statements and arrays!

    Conditional Statement Practice: Candy Machine

    Array & Loop Practice: Student Account Generator (note that this uses a new kind of loop, the times loop. Search online for what this is. If you can't find it, use another loop!)