Ruby Object Oriented Programming

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
Understanding Ruby Logical OperatorsRuby Flow Control


Purchase and download the full PDF and ePub editions of this Ruby eBook for only $8.99


Ruby is an object oriented environment and, as such, provides extensive support for developing object-oriented applications. The area of object oriented programming is, however, large. Entire books can, and indeed have, been dedicated to the subject. A detailed overview of object oriented software development is beyond the scope of Ruby Essentials. Instead we will introduce the basic concepts involved in object oriented programming and then move on to explaining the concept as it relates to Ruby development.


Contents


What is an Object?

An object is a self-contained piece of functionality that can be easily used, and re-used as the building blocks for a software application.

Objects consist of data variables and functions (called methods) that can be accessed and called on the object to perform tasks. These are collectively referred to as members.

Just about everything in Ruby, from numbers and strings to arrays is an object.

What is a Class?

Much as a blueprint or architect's drawing defines what an item or a building will look like once it has been constructed, a class defines what an object will look like when it is created. It defines, for example, what the methods will do and what the member variables will be.

New classes can be created based on existing classes, a concept known as inheritance. In such a scenario the new class (known as the subclass) inherits all the features of the parent class (known as the superclass) with added features that differentiate it from the superclass. Ruby supports single inheritance in that a subclass can only inherit from a single superclass.

Other languages such as C++ support multiple inheritance where the subclass can inherit the characteristics of multiple superclasses.


Defining a Ruby Class

For the purposes of this tutorial we will create a new class intended to be used as part of a banking application. Classes are defined using the class keyword followed by the end keyword and must be given a name by which they can be referenced. This name is a constant so must begin with a capital letter.

With these rules in mind we can begin work on our class definition:

class BankAccount
   def initialize ()
   end

   def test_method
        puts "The class is working"
   end
end

The above example defines a class named BankAccount with a single method called test_method which simply outputs a string. The initialize method is a standard Ruby class method and is the method which gets called first after an object based on this class has completed initialization. You can place any code in the initialize method and it is particularly useful for passing in arguments when the class is created.

Creating an Object from a Class

An object is created from a class using the new method. For example, to create an instance of our BankAccount class we simply perform the following:

account = BankAccount.new()

This creates a BankAccount object named account. Having created the object we can call our test_method:

account.test_method
The class is working

Instance Variables and Accessor Methods

Instance variables are variables defined in a class that are available only to each instance of the class. Instance variables may be defined either inside or outside of class methods. To make the variables available from outside the class, they must be defined within accessor methods (also known as a getter method).

For example, we might want to add instance variables to our BankAccount class:

class BankAccount

   def accountNumber
        @accountNumber = "12345"
   end

   def accountName
        @accountName = "John Smith"
   end

   def initialize ()
   end

   def test_method
        puts "The class is working"
        puts accountNumber
   end
end

Now we have two instance variables called @accountNumber and @accountName with associated accessor methods. We can now access these variables from outside the

account = BankAccount.new()
puts account.accountNumber
puts account.accountName

The two puts statements above will print out the values of the two variables returned by the accessor methods (in this case "12345" and "John Smith" respectively).

Now that we can "get" the value of an instance variable, we now need a way to "set" the value of an instance variable. One way to do this is via a setter methods. Let's clean up our BankAccount class, so that it has two instance variables with getters and setters:

class BankAccount

   def accountNumber
        @accountNumber
   end

   def accountNumber=( value )
        @accountNumber = value
   end

   def accountName
        @accountName
   end

   def accountName=( value )
        @accountName = value
   end

end

We can now create an instance of our class, set the name and account number using the setters and then access them using the getters:

account = BankAccount.new()

account.accountNumber = "54321"     
account.accountName = "Fred Flintstone"

puts account.accountNumber
puts account.accountName

Ruby Class Variables

A class variable is a variable shared between all instances of a class. In other words, there is one instance of the variable and it is accessed by object instances. An instance variable must be initialized within the class definition. Class variables are prefixed with two @ characters (@@).

To demonstrate this we will add an @@interest_rate class variable (since the same interest rate applies to all back accounts):

class BankAccount

   def interest_rate
        @@interest_rate = 0.2
   end

   def accountNumber
        @accountNumber
   end

   def accountNumber=( value )
        @accountNumber = value
   end

   def accountName
        @accountName
   end

   def accountName=( value )
        @accountName = value
   end

end

Instance Methods

Although we looked briefly at instance methods earlier in this chapter we have so far focused on storage of data in a class.

Instance methods are methods that can be called on an instance of the class. Instance methods can access class variables to perform tasks, and can also accept values as arguments. For example, we can add a method to our class that takes a new account balance as an argument and use the @@interest_rate class variable to calculate the interest due:

   def calc_interest ( balance )
       puts balance * interest_rate
   end

Now, when we create an instance of our class, we can call the new method:

account = BankAccount.new()
account.calc_interest( 1000 )
700.0

Ruby Class Inheritance

As we mentioned earlier in this chapter, Ruby supports single inheritance. This means that a subclass can be created that inherits all the variables and methods of another class. The subclass is then extended to add new methods or variables not available in the superclass.

One class inherits from another using the < character. Say, for example, that we want a new kind of BankAccount class. This class needs all the same variables and methods as our original class, but also needs the customer's phone number. To do this we simply inherit from BankAccount and add the new instance variable:

class NewBankAccount < BankAccount

   def customerPhone
        @customerPhone
   end

   def customerPhone=( value )
        @customerPhone = value
   end

end

We now have a new class, derived from BankAccount. This new subclass has everything the superclass had, plus a new property - the customer's phone number:

account.accountNumber = "54321"
account.customerPhone = "555-123-5433"
54321
555-123-5433

Note that the above example assumes the declaration of the BankAccount class is in the same Ruby source file as the NewBankAccount declaration. If this is not the case, the require statement must be used to tell Ruby which file to include to find the BankAccount class. Assuming that BankAccount is defined in a file named "BankAccount.rb" we would include the file as follows:

require 'BankAccount'

class NewBankAccount < BankAccount

   def customerPhone
        @customerPhone
   end

   def customerPhone=( value )
        @customerPhone = value
   end

end


Purchase and download the full PDF and ePub editions of this Ruby eBook for only $8.99



PreviousTable of ContentsNext
Understanding Ruby Logical OperatorsRuby Flow Control