Object and Classes in Ruby
Overview
Ruby is a dynamic, object-oriented programming language that is designed to be easy to use and read. Object-oriented programming is a programming paradigm that models the world in terms of objects and classes, and Ruby is an excellent example of an object-oriented programming language. In this article, we will explore the concepts of objects and classes in Ruby and understand how they work.
Ruby: Classes and Objects
Class is a blueprint of an object. It defines the attributes (characteristics) and methods (actions) of the objects that will be created from it.
A Car class can be used to create different types of car objects with their own unique properties such as make, model, year, colour, and mileage. Each car object can also have methods to accelerate, brake, and change gears.
The object is an instance of the class which means it has the same attributes and methods of the class but with unique features.
The above car class can have two objects car1(make: Toyota, model: Corolla, year: 2020, colour: Blue, mileage: 10000) and car2(make: Toyota, model: Corolla, year: 2020, colour: Red, mileage: 10000). Only the colour property of both the cars are different, rest all are the same.
Ruby: Class Hierarchy
All classes in Ruby are organized in a hierarchy. It is a tree-like structure where each class has one superclass, except for Object Class, which is the root of the hierarchy and has no superclass. Since Object Class is at the top of the hierarchy, it defines a set of default methods that are inherited by every other class in Ruby. These default methods can be overridden by subclasses to modify their behavior. All classes in Ruby ultimately inherit from Object Class.
How to Define Classes in Ruby
In Ruby, you can define a class using the class keyword, followed by the name of the class, and then the body of the class is enclosed in the end keyword. The class body contains the methods and attributes that define the behavior of the class.
Syntax
Example
In the example above, the class MyClass is defined with an initialize method and a my_method method. The initialize method is a special method that is called when a new instance of the class is created using the new method. The @arg1 and @arg2 variables are instance variables that can be accessed from within any method of the class.
Variables in Ruby Class
There are three types of variables that can be used in classes in Ruby: instance variables, class variables, and global variables.
Instance variables start with the @ symbol and are only accessible within the instance of the class where it is defined. Class variables begin with the @@ symbol and are shared among all instances of a class. It is accessible from both class and instance methods Global variables begin with a $ symbol and can be accessed from anywhere in the code.
Defining Methods in Ruby Classes
Classes in Ruby can define methods that can be used by objects of that class. These methods can perform various tasks and can be called on the object using dot notation. In this section, we will discuss how to define methods in Ruby classes.
Syntax
Here, we define a method called method_name that takes two arguments, argument1 and argument2. The method body contains the code that is executed when the method is called.
Example
In this example, we have defined two methods in the Person class: greetings and change_name. The greetings method prints a greeting, while the set_name method takes a new_name argument and changes the value of the @name instance variable to new_name.
How to Create Objects from A Ruby Class?
We can create an object of the classes in Ruby using the new method. The new method is a built-in method that is defined in the Object class and is inherited by every other class.
Syntax
Example
In this example, we have created a new object of the MyClass class and assigned it to the variable my_object. We have also passed the 10 and 20 as an argument to the initializer method. This creates the instance of MyClass with @arg1 set to 10 and @arg2 set to 20.
New Method to Create Object in Ruby Class
Classes in Ruby use the new method to create a new object of a class. This method is defined by the Ruby language itself and is available to all classes. When the new method is called on a class, it creates a new object of that class and returns it.
Syntax
Example
In this example, we have created a new object of the Person class using the new method and assigned it to the variable person. We have then called the greetings method on the person object.
Creating Objects using Custom Methods in Ruby
We can also define custom methods to create objects of classes in Ruby. This can be useful if we want to create objects with specific attributes or if we want to validate the input before creating the object.
Syntax
Example
Here are some examples of how to create objects of the Person class with different parameters:
In this example, the Person class has an initialize method that takes three parameters (name, age, and occupation) and sets the three instance variables (@name, @age, and @occupation) to their values. It also has a greetings method that outputs a message containing the name, age, and occupation of the person.
Member Functions in Ruby Classes
In Ruby, member functions are methods that can be called on instances of a class. They are defined within the class definition using the def keyword. They are accessible to instances of the class. In the above example, greetings is a member function of the class Person. By defining member functions within a class, you can give instances of the class-specific behaviors and properties that can be manipulated and interacted with in various ways.
Example for Understanding
In this example, the BankAccount class has an initialize method that takes a balance parameter and sets an instance variable @balance to its value. It also has two other methods, deposit and withdraw, which can be called on instances of the class to add or remove funds from the account.
The attr_reader :balance line creates a "getter" method for the @balance instance variable, allowing external code to read the current balance of the account without modifying it directly.
To create a new BankAccount object with an initial balance of 100 coins, you can call the new method on the class and pass in the initial balance:
You can then call the deposit and withdraw methods on myaccount to modify the balance:
By defining classes with specific behaviors and properties, you can create reusable code that can be used in various parts of your application.
FAQs
Q: Can a Ruby Class Inherit from Multiple Classes?
A: No, a Ruby class can only inherit from a single class. This is known as single inheritance. However, you can simulate multiple inheritances through the use of modules.
Q: How Do You Call a Superclass Method in Ruby?
A: To call a method from a superclass in Ruby, you use the super keyword within the subclass method. This will call the superclass method with the same name as the subclass method. For example:
In this example, the MySubclass method my_method calls the MyClass method my_method using super, and then adds its own functionality to the method
Q: What Are Some Best Practices for Naming Classes in Ruby?
A: In Ruby, class names should start with a capital letter and use CamelCase to separate words. For example, MyClass or MySubClass.
Conclusion
- Ruby is a powerful object-oriented programming language that enables developers to create classes and objects.
- Classes in Ruby define methods, member functions, and instance variables, and can be used to create objects with specific attributes and behavior.
- Methods in Ruby classes allow developers to perform specific tasks on objects, while member functions provide a convenient way to access and modify instance variables.
- With the new method and custom methods, developers can create objects with specific attributes or validate input before creating the object.
- Ruby classes support inheritance, which reduces code duplication and improves the organization and reusability of code.
- Ruby's object-oriented features provide a flexible and powerful way to structure code and create reusable components.