(7 ratings)   
By: math.umd.edu
There are just a couple more things that we should do with our AddressBook class.
Added: 23 June 2008    Views: 125  
PathComputers    Programming    Ruby
Keywords: computers   programming   ruby   coder   code   language  
Do you like this tutorial? Now you can support our team to add more :     
 
 
 

Private and public methods

Take a look at AddressBook#by_name. This method is different from the other methods in one important respect: It is used only inside the object. It is an internal method.

When you have a method like this, it is best to declare it as private. A private method can only be accessed by the object itself, and never by the user. A regular method, that is available to the user, is called public.

You can declare methods as public and private with the (surprise!) public and private keywords. When you put the keyword private you set all the methods defined from then on as private, until you change it back wit the public keyword.

class SomeClass

def method1 # default to public
...
end

private # subsequent methods are private.

def method2 # private method
...
end
def method3 # private method
...
end

public # Set back to public.

def method4 # public method
...
end
end

So, in our case, we just want to put the private keyword before we define the by_name method.

class AddressBook
#
# Fundamental methods: initialize, add, remove
#
def initialize
@persons = []
end
def add(person)
@persons += [person]
@persons = @persons.sort{|a,b| by_name(a,b)}
end

...

private # Start private methods

#
# Sorting function.
#
def by_name(a,b)
if a.first_name == b.first_name
a.last_name <=> b.last_name
else
a.first_name <=> b.first_name
end
end
end

Code reuse with require

We have spent a lot of time writing these three classes. We don't want to copy and paste the code every time we want to use them in a program. Fortunatelly, we don't have to.

Put all three classes in a file, and save it as addressbook.rb. Now, create a new file (in the same directory) and type:

require "addressbook"

# Sandy

addr = Address.new
addr.street = "324 Campus Dr."
addr.city = "College Park"
addr.state = "MD"
addr.zip = "23659"

puts addr

Run the program, and you should get:

$ ruby prog.rb 
324 Campus Dr.
College Park
MD, 23659
$

The require line lets you reuse your code on any other programs you write.

About the Author :
math.umd.edu
More features IN RUBY
Articles and Tutorials Directory by www.learnfobia.com
 Rate this tutorial : Rate 1Rate 2Rate 3Rate 4Rate 5
  |    Add to Favorites
  |    Send to Friend
  |    Print
Comments