



(7 ratings)
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 |
So, in our case, we just want to put the private keyword before we define the by_name method.
class AddressBook |
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" |
Run the program, and you should get:
$ ruby prog.rb |
The require line lets you reuse your code on any other programs you write.
20 Random Tutorials from the same category :
The Scalability of Ruby
Iterators In RUBY
Printing the addressbook RUBY
Implementing AddressBook In RUBY
Example: Addressbook RUBY
Hashes In RUBY
Writing iterators In RUBY
Difference of Gtk+ and Ruby/Gtk
What can ruby arrays do?
More features IN RUBY
Arrays In RUBY
Sorting the addressbook RUBY
Classes and methods in RUBY
Progress Bars with GD2 and Ruby













