Ruby Class and Object

Here, we will learn about Ruby objects and classes. In object-oriented programming language, we design programs using objects and classes.

Object is a physical as well as logical entity whereas class is a logical entity only.


Ruby Object

Object is the default root of all Ruby objects. Ruby objects inherit from BasicObject (it is the parent class of all classes in Ruby) which allows creating alternate object hierarchies.

Object mixes in the Kernel module which makes the built-in Kernel functions globally accessible.


Creating object

Objects in Ruby are created by calling new method of the class. It is a unique type of method and predefined in the Ruby library.

Ruby objects are instances of the class.

Syntax:

objectName = className.new  

Example:

We have a class named Java. Now, let’s create an object java and use it with following command,

java = Java.new("John")  
Ruby Class and object 1

Ruby Class

Each Ruby class is an instance of class Class. Classes in Ruby are first-class objects.

Ruby class always starts with the keyword class followed by the class name. Conventionally, for class name we use CamelCase. The class name should always start with a capital letter. Defining class is finished with end keyword.

Syntax:


  1. class ClassName  
  2.     codes...  
  3. end  

Example:

Ruby Class and object 2

In the above example, we have created a class Home using class keyword. The @love is an instance variable, and is available to all methods of class Home.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *