Object Oriented Programming

Represents the concept of "objects".

"Objects" have:

Data Fields - attributes that describe the object

Methods - associated procedures

What-Huh Programming?

Object-Oriented Programming!

Give Your Program Some class

class Object




end

We define an object using "class" (and there's end to tell Ruby when the definition is over!).

And then we fill in with our methods.

class Object

    def method1
    
    end
    
    def method2
    
    end

end

instance & Initialization

There's one method we NEED : initialize.

This method will allow for the creation of a new Object.

class Object

    def initialize(attr1, attr2)

        @attr1 = attr1
        @attr2 = attr2

    end

end

We pass the method attributes as arguments,

and set these attributes to corresponding instance variables.

 

Instance variables can be used throughout the class definition.

Variables: instance vs. Local

What's the difference?


# local variable:
name = "Aaron"

def display_name
    puts name
end

# This will result in an error:
# Variable name inside the method is undefined.
# We would need to pass the outside definition of
# 'name' to the method for anything to happen.
# instance variable:
@name = "Aaron"

def display_name
    puts @name
end

# The instance variable can be seen inside 
# the method without passing it as an argument.

Let's get object oriented

Let's spend some time make some Objects...

class Person

    def initialize(name, age)
        @name = name
        @age = age
    end
end

my_profile = Person.new("Aaron", 33)

Create a User object.

Create a Pet object.

Create a Product object.

classy methods

Let's create some methods for our classes.

class Person

    def initialize(name, age)
        @name = name
        @age = age
    end

    def name
        @name
    end

    def age
        @age
    end

end

my_profile = Person("Aaron", 33)

puts "Hi, I am #{my_profile.name} and I am #{my_profile.age}-years-old."

Create methods for the other Objects we created!

methods that do more

class Person

    ...

    def birthday
        @age += 1
    end

    def change_name(name)
        @name = name
    end

end

my_profile = Person.new("Aaron", 33)

puts my_profile.age

my_profile.birthday

puts my_profile.age

puts "I am no longer #{my_profile.name}..."

my_profile.change_name("King Ruby")

puts "My name is now #{my_profile.name}."
Made with Slides.com