Ruby Classes and Objects

Ruby is a perfect object-oriented programming language. The features of object-oriented programming languages include:

  • Data encapsulation
  • Data abstraction
  • Polymorphism
  • Inheritance

These features will beObject-oriented Rubydiscussed in.

An object-oriented program involves classes and objects. A class is a blueprint from which individual objects are created. In object-oriented terminology, your bicycle is an instance of the class of bicycles.

Take vehicles as an example; they include wheels, horsepower, and fuel or gas tank capacity. These attributes form the data members of the Vehicle class. With these attributes, you can distinguish one vehicle from other vehicles.

Vehicles can also contain specific functions, such as halting, driving, and speeding. These functions form the data members of the Vehicle class. Therefore, you can define a class as a combination of attributes and functions.

The definition of the class Vehicle is as follows:

Example

Class Vehicle { Number no_of_wheels Number horsepower Characters type_of_tank Number Capacity Function speeding { } Function driving { } Function halting { } }

By assigning different values to these data members, you can create different instances of the class Vehicle. For example, an airplane has three wheels, 1,000 horsepower, and a fuel tank capacity of 100 liters. In the same way, a car has four wheels, 200 horsepower, and a gas tank capacity of 25 liters.

Defining Classes in Ruby

In order to implement object-oriented programming in Ruby, you need to first learn how to create objects and classes in Ruby.

In Ruby, classes always begin with the keywordclassfollowed by the name of the class. The first letter of the class name should be capitalized. The classCustomeris as follows:

class Customer end

You can use the keywordendto terminate a class.ClassAll data members are placed between the class definition and theendkeyword.

Variables in Ruby Classes

Ruby provides four types of variables:

  • Local variables:Local variables are variables defined within a method. Local variables are not available outside the method. In subsequent chapters, you will see more details about methods. Local variables begin with a lowercase letter or _.
  • Instance variables:Instance variables can be used across methods within any particular instance or object. This means that instance variables can change from object to object. Instance variables have the symbol (@) placed before the variable name.
  • Class variables:Class variables can be used across different objects. Class variables belong to the class and are an attribute of the class. Class variables have the symbol (@@) placed before the variable name.
  • Global variables:Class variables cannot be used across classes. If you want to have a variable that can be used across classes, you need to define a global variable. Global variables always begin with the dollar sign ($).

Example

Using the class variable @@no_of_customers, you can determine the number of objects created, thus determining the number of customers.

Example

class Customer @@no_of_customers=0 end

In Ruby, using thenewmethod to create objects

Objects are instances of classes. Now you will learn how to create objects of a class in Ruby. In Ruby, you can use the class methodnewto create objects.

The methodnewis a special method, predefined in the Ruby library. The new method belongs to theClassmethod.

The following example creates two objects of the class Customer, cust1 and cust2:

cust1 = Customer. new cust2 = Customer. new

Here, cust1 and cust2 are the names of the two objects. The object name is followed by an equals sign (=), the equals sign is followed by the class name, then the dot operator and the keywordnew。

Custom Methods to Create Ruby Objects

You can pass to the methodnewparameters, which can be used to initialize class variables.

When you want to declare a method with parametersnewmethod, you need to declare the method while creating the class.initialize。

initializeThe method is a special type of method, which will be executed when the class with parameters'newmethod is called.

The following example creates the initialize method:

Example

class Customer @@no_of_customers=0 def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr end end

In this example, you can declare a method withid、name、addras local variablesinitializemethod. Here,defandendis used to define Ruby methods.initializeIn subsequent chapters, you will learn more details about methods.

IninitializeIn the method, the values of these local variables are passed to the instance variables @cust_id, @cust_name, and @cust_addr. Here, the values of the local variables are passed along with the new method.

Now, you can create objects as follows:

cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2=Customer.new("2", "Poul", "New Empire road, Khandala")

Member Functions in Ruby Classes

In Ruby, functions are called methods.ClassEvery method in it starts with the keyworddeffollowed by the method name.

Method names alwayslowercase lettersbegin with. In Ruby, you can use the keywordendto end a method.

The following example defines a Ruby method:

class Sample def function statement 1 statement 2 end end

Here,statement 1andstatement 2is the method inside the class Sample,functionand the following are the components of its body. These statements can be any valid Ruby statements. For example, we can use the methodputsto outputHello Ruby, as follows:

class Sample def hello puts "Hello Ruby!" end end

The following example creates an object of the class Sample and calls thehellomethod:

#!/usr/bin/ruby class Sample def hello puts "Hello Ruby!" end end #Using the above class to create objects object = Sample. new object.hello

This will produce the following result:

Hello Ruby!

Simple Case Study

If you want to do more exercises on classes and objects, here is a case study:

Ruby Class Examples

Other Extensions