Home » Ruby Class and Object

Ruby Class and Object

by Online Tutorials Library

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:

Example:

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

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:

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.


Next TopicRuby methods

You may also like