Intro to Ruby

Class 3

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

  • Conditions - if, elsif, else
  • Loops - while, times, each
  • Arrays - [1,2,3]

What we will cover today

  • Hashes
  • Methods
  • Objects
  • Object Oriented Programming

Hashes

Hashes are indexed collections like arrays. Each value in a hash actually has two elements, a key and a value. They can be filled with any data type: integers, floats, strings, even arrays and hashes.


    grades_hash = { 
      "Heather" => 10,
      "Tasha" => 8
    }

    new_hash = { 
      1 => "number one!",
      "num_one" => 12, 
      "num_two" => 35
    }

    # some methods to find information about hashes 
    new_hash.length
    grades_hash.has_key?("Tasha")
    new_hash.has_value?(35)
                

Symbols as Hash Keys

Symbols are often used as keys of hashes.

Think of them as another Ruby object that has its own methods.


    food = { 
      "apple" => "a fruit",
      "carrot" => "a vegetable"
    }

    food = { 
      :apple => "a fruit",
      :carrot => "a vegetable"
    }

    # another way to use symbols in hashes!
    # notice the hash rockets can be removed in this case
    food = {
        apple: "a fruit",
        carrot: "a vegetable"
    }
                

Accessing Elements in Hashes

Hashes are unordered. Hashes are like dictionaries, with unique key / value pairs.

Because hashes can hold any type of objects, and are unordered, we must access values by their key.


  grades_hash = { "Tasha" => 12, "Joe" => 10, "Heather" => 8 }
  new_hash = { 1 => "a number!", "num_one" => 12, "num_two" => 35 }
  food_hash = { apple: "a fruit", carrot: "a vegetable" }

  grades_hash["Joe"]        # returns 10, the value of this key
  grades_hash.first         # returns first key/value pair... probably

  new_hash["num_one"]       # returns 12, the value of this key

  food_hash[:carrot]        # accessing hash with symbols as keys
          

Adding & Removing from Hashes


    new_hash = { 1 => "a", "d" => 12, "f" => 35 }

    # add
    new_hash["z"] = 43   # adds a new key/value pair "z" => 43 

    # remove
    new_hash.delete("d") # removes key/value pair with specified key   
    new_hash.clear       # removes all key/value pairs 
          

More Hash methods


    chapters = {
        "My Early Home" => (1..15),
        "The Hunt" => (16..28), 
        "My Breaking In" => (29..46),
        "Birtwick Park" => (46..60)
    }

    chapters.count      # returns number of key/value pairs in hash
    chapters.keys       # returns an array of all the keys in hash
    chapters.has_key?("How It Ended")  # returns a boolean
    chapters.to_a       # converts hash to an array of arrays
    chapters.invert     # returns new hash with keys and values switched
          

Learn more about hashes here.

Methods

A method is a name for a chunk of code that we can use to perform a specific task.

Methods are often used to define reusable behavior.

Let's look at a couple of methods we've already used:


	1.even?
	=> false

	"jordan".capitalize
	=> "Jordan"
	        

If you have some code you want to reuse or organize, methods will help.

Write a Method

Let's write a method together

def means define

subtract is the name of the method

num_one, num_two are parameters

num_one - num_two is the body of the method

num_one - num_two is also the return value


    def subtract(num_one, num_two)
      num_one - num_two
    end
            

Let's Develop It!

Let's write a method that takes in a number and tells us if it is even.

Hint: if number % 2 == 0, then it is even


          def method_name(parameter)
            # method implementation
          end
            

Method Return Value

Every Ruby method returns something.

Usually, it's the last statement in the method.

It could be the value sent to return if that came first.


    def subtract(num_one, num_two)
      num_one - num_two
      'another thing'
    end

    return_value = subtract(5, 2)
    puts return_value

    def subtract(num_one, num_two)
      return num_one - num_two
      'another thing'
    end

    return_value = subtract(5, 2)
    puts return_value
            

Arguments vs. Parameters

Technically speaking, arguments are passed and parameters are declared.

Note that the variable names don't have to match!

In this code, 5 is an argument and num_one is a parameter


    def subtract(num_one, num_two)
      num_one - num_two
    end

    subtract(5, 2)
            

Splat Arguments


    def greet(greeting, *names)
      # names is now an array we can iterate through!
      names.each do |name|
        puts "#{greeting}, #{name}!"
      end
    end

    greet("Hello", "Alice", "Bob", "Charlie")
    Hello, Alice!
    Hello, Bob!
    Hello, Charlie!
            

Default Parameters

We can set our method parameters to have a default value if no arguments are passed to it.


    def eat(food = "chicken")
      puts "Yum, #{food}!"
    end

    eat
    Yum, chicken!

    eat("kale")
    Yum, kale!
            

Named Parameters

To pass variable parameters, or to pass named parameters, you can use an options hash


    def bake(name, options = {})
        flour = options[:flour] || "wheat"
        creamer = options[:creamer] || "cream"
        puts "Baking a nice #{name} loaf with #{flour} flour and #{creamer}"
    end

    bake("Sourdough")
    bake("Gluten-Free", flour: "rice", creamer: "milk")
    bake("Pumpernickel", creamer: "butter")
            

Objects

An Object is the building block of a program.

Objects do things and have properties.


Object: Number

What can it do?

add, subtract, multiply, divide


What are some properties of your Number?

odd, even

Object Class

Objects can be grouped by Class.

Classes define a template for objects. They describe what a certain type of object can do and what properties they have in common.

There are many kinds of objects, including String, Number, Array, Hash, Time...

To create an object we use .new


    array = Array.new
          

'array' now refers to an object instance

Object Methods

Methods can be defined on objects.


    # Object is the default root of all other Ruby objects
    # We can create an instance of Object as well!
    my_object = Object.new

    def my_object.say_hello
      puts "Hello, World!"
    end

    my_object.methods
            

Instance Variables

Represent object state

Names start with an @

Only visible inside the object


    cookie = Object.new

    def cookie.add_chocolate_chips(num_chips)
      @chips = num_chips
    end

    def cookie.yummy?
      @chips > 100
    end

    cookie.add_chocolate_chips(500)
    cookie.yummy?   # => true
            

What would happen if we called our yummy? method before add_chocolate_chips?

Object Oriented Programming

  • Object Oriented Programming is one of many programming approaches: procedural, event-driven, functional, declarative...
  • These days, most programming is done in an OO language: Java, Python, C#, C++.
  • All this means is that programs are organized around objects (data & methods).
  • You might choose OOP because Objects make things easier to understand and act as a natural way to modularize code. When a large code base is composed of many small Objects, it is easier to maintain and change.

OOP & Easy Understanding

Objects often take on names from their domain which makes them easy to conceptualize.


For example, without seeing code, you can probably guess what an object called 'Bike' or 'Chair' can do (or not do), and what attributes it might have (or not have).

OOP & Encapsulation

One thing that makes code easier to maintain is Encapsulation, which is one of the fundamentals of OOP.

Encapsulation is a nice way of saying 'put all my properties/behaviors in my capsule where other objects can't touch them'.

By assigning certain responsibilities to objects, code is more purposeful and less likely to be changed by accident.

OOP & Inheritance

Just as you inherited traits from your parents, your objects may inherit traits from other objects.

Inheritance is when you use one class as the basis for another.

You might use Inheritance if two objects have the same properties and methods. This way you don't need to write the same thing twice.

OOP & Polymorphism

  • Similar to inherited traits and behaviors, there are also polymorphic traits and behaviors.
  • Polymorphic means many forms.
  • Within OOP, this relates to different objects being able to respond to the same message in different ways.

Homework

Practice: Read Chapter 8 of Learn to Program and do some of the exercises at the end.

Prep: Read Chapter 9 of Learn To Program - don't try to do the exercises at the end yet, though.