<- Classes and methods
Implementing AddressBook ->

More on classes

Class Person

Now let's create a Person class. We said that a person should have a first name, last name, email and address.


class Person
    attr_accessor :first_name, :email
    attr_accessor :last_name, :address  
    def initialize
        @first_name = @last_name = @email = ""  
        @address = Address.new
    end
end
                       

The only thing new here is the "@address = Address.new" line. @address is not a string, but an Address object, so we must create it as such.

Now we can create a person:


sandy_addr = Address.new
sandy_addr.street = "324 Campus Dr."  
sandy_addr.city   = "College Park"

sandy = Person.new
sandy.first_name = "Sandy"
sandy.last_name  = "Koh"
sandy.address = sandy_addr
                       

Notice that we didn't put down a state, zip or an email. Since we default all values to "", we are free to creat an Address and a Person object with incomplete information. We can still call sandy.email without trouble. We will just get "" in return.

Now let's add some more behaviour to Person. Let's add a method that returns the full name of the person.


class Person
    def full_name
        @first_name + " " + @last_name  
    end
end

puts sandy.full_name

                       

This prints "Sandy Koh".

Printing a class

Wouldn't it be nice if we could just type "puts address"? We can make that happen.

The puts function works by calling Class#to_s and sending the result to the terminal (remember Integer#to_s and friends?). So, what we need to do is define an Address#to_s method.


class Address
    def to_s
        "    " + @street + "\n" + \
        "    " + @city   + "\n" + \
        "    " + @state  + ", " + @zip  
    end
end
                       

What's that "\n"? It indicates a "new line" character. It is the character that your keyboard sends when you press the "Enter" key. The "\" at the end of each line ensures that this is all read as one statement. The resulting string is returned.

Now we can type:


address.street = "23 St George St."  
address.city   = "Silver Spring"
address.state  = "MD"
address.zip    = "20465"

puts address
                       

Which prints:


    23 St George St.  
    Silver Spring
    MD, 20465
                       

Exercises

  1. Write a Person#to_s method that prints the person's full name, email, address and phone. Use the Address#to_s method we just wrote.

<- Classes and methods
Implementing AddressBook ->