Intro to Programming with Ruby

Class 3

Welcome!

Girl Develop It is here to provide affordable programs for adult women interested in learning web and software development in a judgment-free environment.

Some "rules"

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

Girl Develop It is dedicated to providing a harrasment free learning experience for everyone.
For more information, see our Code of Conduct.

Homework Discussion

How was last week's homework?

Do you have any questions or concepts that you'd like to discuss?

Is anyone BRAVE enough to show what they have?

The Homework was:
  • Ranges problem
  • Pet shop
  • Bye Grandma

HW: grandma.rb


                      chatting = true
                      byes = 0
                      while chatting
                        puts "Ask Grandma a question:"
                        said = gets.chomp!
                        if said == "BYE"
                          byes += 1
                            if byes > 2
                              chatting = false
                            else
                              puts "** Grandma is ignoring you **"
                            end
                        elsif said == said.upcase
                          year = 1930 + Random.rand(20)
                          puts "NO, NOT SINCE #{year}!"
                        else
                          puts "HUH?!  SPEAK UP, SONNY!"
                        end
                      end
                      puts "Thanks for chatting with Grandma"
                    

Review

  • Conditions - if, elsif, else
  • Loops - while, for
  • Arrays - [1,2,3]
  • Ranges - [1..3]
  • Hashes - {"one" => 1, "two" => 2}

What we will cover today

  • Methods / Functions
  • Objects
  • Object Oriented Programming

Methods

A method is a name for a chunk of code

Methods are often used to define reusable behavior.

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


                        1.even?
                        => false

                        "fred".capitalize
                        => "Fred"

                        "fred".class
                        => String
                        

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

Method VS Function

Question: "Are methods and functions the same thing?"

Answer: "For the most part"

Functions are chunks of code you can re-use

Methods are Functions that exist on objects

Doesn't make sense? Don't worry! It's not really that important right now!

For the purpose of this class, call them whichever word you want

Writing A Method

Just like with loops and conditionals there is a term used to declare a method, def and end


                      def subtract(x, y)
                        x - y
                      end
                    

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

Calling A Method

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

Class: Write this code into irb and call out what the results are!


                      def subtract(x,y) #parameters
                      x - y
                      end

                      subtract(5, 2) #arguments
                    

Returning Values

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.

Class: Write this code into irb and call out what the results are!


                      def subtract_a(x,y)
                      x - y
                      'another thing'
                      end

                      return_value = subtract_a(5, 2)
                      puts return_value

                      def subtract_b(x,y)
                      return x - y
                      'another thing'
                      end

                      return_value = subtract_b(5, 2)
                      puts return_value
                    

Local Variables

A local variable is a variable whose scope ends (goes out of context) when the function returns

Class: Write this code into irb and call out what the results are!


                      def doubleThis num
                        numTimes2 = num*2
                        puts num.to_s+' doubled is '+numTimes2.to_s
                      end

                      doubleThis 44
                      puts numTimes2.to_s
                    

                      44 doubled is 88
                      # >
                    
                  

Splat Arguments

Only in 1.9 or newer

The Splat or asterisk operator will capture however many arguments you pass into greet.

If you might want to pass in a different number of arguments each time, a Splat argument might be the right choice!


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

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

For more explaination check out this link

Default Values

If using 1.9 or lower, these have to be the last arguments in your list.

Default values are used if the caller doesn't pass them explicitly.


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

                      >> eat
                      Yum, chicken!

                      >> eat "arugula"
                      Yum, arugula!
                    

Hashes as 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})
                    

Let's Develop It!

Lets write a method called calculator. It will take 2 numbers, like 22 and 5, and a string like "divide". For now, just do "add", "subtract", "multiply", and "divide"

Cheat!

Here is some help to get started


                      def calculate(first_num, second_num, operation)
                        # Do something different based on operation!
                      end
                    

Objects and Classes

"A Class is to an Object like a Book is to Mary Shelley's Frankenstein"

Classes

Everything has a Class.

Classes define a template for objects. They describe what a certain type of object can do and what properties it has.

There are many kinds of classes you've already been using, including:
String, Number, Array, Hash, Time, ...

Objects

An Object is an instance of a Class

Objects do things and have properties.

To create an instance of a class (aka: Object) we use .new


                          arr = Array.new
                        

arr now refers to an instance of the class Array

Object: Number

What can it do?

  • Add +
  • Subtract -
  • Divide /
  • Multiply *

Sample properties?

  • len - What is the length?
  • base - What base is the number in? (2, 10, 16?)
  • even - Is the number even, or odd?

Object Methods

Methods can be defined on objects.

Class: Write this code into irb and call out what the results are!


                      class MyObject
                        def delete
                          puts "Deleted the thing!"
                        end
                      end

                      o = MyObject.new

                      puts o.methods.include?(:delete)
                    

Instance Variables

Represent object state

Names start with an @

Only live inside the object

Class: Write this code into irb and call out what the results are!


                      class Cookie
                        def add_chips(num_chips)
                          @chips = num_chips
                        end

                        def yummy?
                          @chips > 100
                        end
                      end

                      cookie = Cookie.new
                      cookie.add_chips(500)
                      puts cookie.yummy?
                    

Object Oriented Programming

  • Object Oriented Programming is one of many paradigms of programming: procedural, event-driven, functional, declarative...
  • It's very common to encounter OOP in most companies, and especially in certain languages: Java, Ruby, C#, Python
  • ... But! Some languages are good at more than one paradigm! (We're going to focus on OOP, though)
  • 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.

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.

Real World Example: You don't need to know how the engine works to drive your car - you just need to know Start, Accelerate, Slow, and Off

OOP & DRY

DRY stands for Don't Repeat Yourself

Code is said to be DRY when you don't have any copy/pasted code in multiple places - when each line that can be re-used, is.

DRY goes well beyond just OOP, but OOP makes DRY code easy, since everything lives in a class or object that you can re-use!

Think about how you can use Encapsulation to make your code more DRY

OOP & Inheritance

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

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

You might use Inheritance if two classes have the same properties and methods, but one will add some additional functionality the other doesn't need.
This way you don't need to write the same thing twice.


                          class MyString < String
                          end

                          my_string = MyString.new
                          my_string.upcase
                        

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.


                          [1, "abc"].each {|object| puts object.next}
                        

Questions?

Homework

Expand upon the calculate method from class.

Make a class called "Calculator", and make each operation ("add", "subtract", "multiply","divide") into a method on Calculator

Run a demonstration of having all of the operations return a correct result!

Intro to Programming in Ruby

@gdiboston


We are done with class 3!

We have done a lot, I know you have questions so ask them!

Setup   |   Class 1   |   Class 2   |   Class 3   |   Class 4