ruby
  1. ruby-oops

Ruby Object Oriented Programming (OOPs)

Syntax

class MyClass 
  def initialize
    #Constructor
  end
  
  def method_name(parameters)
    #Method body
  end
end

Example

class Circle
  Pi = 3.1416
  
  def initialize(radius)
    @radius = radius
  end
  
  def area
    Pi * @radius * @radius
  end
  
  def circumference
    2 * Pi * @radius
  end
end
  
circle = Circle.new(5)
puts circle.area
puts circle.circumference

Output

78.54
31.416

Explanation

In Ruby, Object Oriented Programming is based on classes and objects. A class is a blueprint for creating objects, while objects represent the instances of a class. In the above example, we have defined a "Circle" class with three methods: "initialize", "area", and "circumference". The initialize method acts as a constructor and is used to initialize the instance variables of the class. The "area" and "circumference" methods are used to calculate the area and circumference of a circle respectively, using the values of its radius.

Use

Object Oriented Programming is used to create reusable code, where classes represent real-world entities with their own behaviors. It enables code reusability and modularity, making code more efficient and easier to read.

Important Points

  • Classes are defined using the "class" keyword in Ruby.
  • Objects are created using the "new" keyword and constructor.
  • Instance variables are created using the "@" symbol and the variable name.
  • Methods are defined using the "def" keyword followed by the method name and its parameters.
  • OOPs concepts include encapsulation, inheritance, and polymorphism.

Summary

In summary, Ruby OOPs is a powerful feature of the language, enabling programmers to create modular, efficient and reusable code. It is based on the concepts of classes and objects, and includes features such as encapsulation, inheritance and polymorphism. The above example demonstrates the creation of a simple "Circle" class to showcase the basics of Ruby OOPs.

Published on: