GDI Logo Badge

Intro to Ruby

Class 3

Welcome!

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

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, each
  • Ranges - (0..10)
  • Arrays - [1,2,3]
  • Hashes - {"one" => 1, "two" => 2}

What we will cover today

  • Enumerable Methods on Collections- .each()
  • Methods
  • Objects
  • Object Oriented Programming

Enumerable

Arrays and Hashes are both classes that have Enumerable methods. There are a lot of cool methods available for Enumerable, including each.

.each with Ranges

This is the simplest!


(3..8).each do |number|
  puts number * 4
end
            

.each with Arrays

Can be simple or more complex, depending on the array.


pets_array = ["dog", "cat", "turtle", "parakeet", "ferret"]

pets_array.each do |pet|
  puts "I like #{pet}s!!"
end


deep_array = [["mountain", "desert"], ["ocean", "sky"]]

deep_array.each do |array|
  puts "I like #{array.first}s!!"  # each element is also an array
end
            

.each with Hashes

Each element has a key and value that needs to be used.


grades_hash = { "Jane Doe" => 10, "Jim Doe" => 6, "Jan Doe" => 8}

grades_hash.each do |key, value|
  puts "#{key}'s grade is #{value}"
end 
            

Let's Develop It

Write a program called 'divisible.rb' that prints out every number between 1 and 1000 that is divisible by 7.


Make a new ruby file called divisible.rb


Hint: the modulo operator, %, will be helpful.

Write out your program in prose, then translate each line into Ruby


# try these expressions in IRB
9 / 2
9 % 2
            

Methods

A method is a name for a chunk of code that goes together.

Methods are often used to define reusable behavior.

Let's look at a method we've already used:


1.even?
=> false

"fred".capitalize
=> "Fred"
          

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

Let's Develop It!

Find the methods available on String and Integer

Do they have any similar methods?


"abc".next
=> "abd"

"abz".next
=> "aca"

1.next
=> 2

-1.next
=> 0
          

Write a Method

Let's write a method together

def means define.

subtract is the name of the method.

x, y are parameters.

x - y is the body of the method.

x - y is also the return value.


def subtract(x, y)
  x - y
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(x,y)
  x - y
  'another thing'
end

return_value = subtract(5, 2)
puts return_value

def subtract(x,y)
  return x - y
  '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 x is a parameter.


def subtract(x,y)
  x - y
end

subtract(5, 2)
          

Splat Arguments


def greet(greeting, *names)
  names.each do |name|
    puts "#{greeting}, #{name}!"
  end
end

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

Default Values


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

eat()
Yum, chicken!

eat("arugula")
Yum, arugula!
          

Default Hash Parameter


def add_to_x_and_y(amount, vals)
  x = vals[:x]
  y = vals[:y]
  x + y + amount
end

add_to_x_and_y(2, {:x => 1, :y => 2})
          

Named Parameters

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


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

bake("Wheat")
bake("Sourdough", :flour => "sour")
bake("Pumpernickel", :creamer => "butter")
          

Methods & Variables

Local vars are only available in the methods where they were defined.


# Let's extract the length of the padded string into
# a local variable
def message(our_string)
  length = 80
  puts our_string.center(length, "-")
end

def different_message(some_string)
  puts our_string.center(length, "=")
end
# Error! 'our_string' and 'length' are not defined inside this method 
          

Objects

An Object is the building block of a Ruby program.


Objects do things and have properties.

Objects


Object: Number

What can it do?

  • Add and subtract
  • Multiply and divide
  • And more...

What are some properties of Number?

  • Length
  • Base
  • Even? or odd?
  • And more...

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, ...

Object Class

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.


array = Object.new

def array.delete
  puts "deleted the array"
end

array.methods(false)
          

Instance Variables

Represent object state

Names start with an @

Only visible inside the object


cookie = Object.new

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

def cookie.yummy?
  @chips > 100
end

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

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, C#, C++.

Object Oriented Programming

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 my code, you can probably guess what an object called 'Bike' can do (or not do).

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.

OOP & Inheritance

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.


class MyString < String
end

my_string = MyString.new
my_string.upcase
          

Questions?

Homework

Practice: Starting with the first "English Number" excercise, do the exercises at the end of Chapter 8 of Learn to Program.

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