SoFunction
Updated on 2025-04-07

Further dive into the concept of classes and objects in Ruby

Ruby is a pure object-oriented language, and all projects seem to be a single object in Ruby. Each value in Ruby is an object, even the most primitive thing: strings, numbers, and even true and false. Even if a class itself is an object, it is an instance of the Class class. This chapter will involve Ruby's object-oriented through all functions.

Classes are used to specify objects in the form, which combines data representations and methods to manipulate this data and convert them into a neat package. In a class data and methods are called members of the class.
Ruby class definition:

Define a class, a sketch of the data type defined. This does not actually define any data, but it defines what the class name means, that is, what class object will include what operations can be performed on such an object.

The class definition begins to be separated from the keyword class name and end. For example, we define the Box class using the class keyword as follows:

class Box
   code
end

The name must start with capital letters, and it contains multiple words in the convention name, each word has no separator (camel).
Define Ruby's object:

Classes are blueprints for objects, so basically one is created from a class object. We declare an object of a class to use the new keyword. The following statement declares two objects, the Box class:

box1 = 
box2 = 

Initialize method:

The initialize method is a standard Ruby class method, and works in the same way as other object-oriented programming language constructors. The initialize method is useful. When creating an object, some class variables are initialized. This method may require a list of parameters, which is defined like other Ruby previous methods with the def keyword, as shown below:

class Box
   def initialize(w,h)
      @width, @height = w, h
   end
end

Instance variables:

An instance variable is an attribute of a class, once the class object we use is created. The properties of each object are assigned separately and shared with other objects. They are accessed internally using the @ operator, but outside of the class, the public method we use is called the accessor method. If we put the above-defined class Box, then the @width and @height class Box instance variables.

class Box
  def initialize(w,h)
   # assign instance avriables
   @width, @height = w, h
  end
end

Accessor and setter methods:

In order to externally access variables of the class, they must define accessor methods, also known as getter methods. The following example demonstrates how to use the accessor method:

#!/usr/bin/ruby -w

# define a class
class Box
  # constructor method
  def initialize(w,h)
   @width, @height = w, h
  end

  # accessor methods
  def printWidth
   @width
  end

  def printHeight
   @height
  end
end

# create an object
box = (10, 20)

# use accessor methods
x = ()
y = ()

puts "Width of the box is : #{x}"
puts "Height of the box is : #{y}"

When the above code is executed, it produces the following results:

Width of the box is : 10
Height of the box is : 20

Similar access methods are used to access variable values. Ruby provides a method to set the values ​​of these variables from outside the class, that is, the setter method??, defined as follows:

#!/usr/bin/ruby -w

# define a class
class Box
  # constructor method
  def initialize(w,h)
   @width, @height = w, h
  end

  # accessor methods
  def getWidth
   @width
  end
  def getHeight
   @height
  end

  # setter methods
  def setWidth=(value)
   @width = value
  end
  def setHeight=(value)
   @height = value
  end
end

# create an object
box = (10, 20)

# use setter methods
 = 30
 = 50

# use accessor methods
x = ()
y = ()

puts "Width of the box is : #{x}"
puts "Height of the box is : #{y}"

When the above code is executed, it produces the following results:

Width of the box is : 30
Height of the box is : 50

Example method:

In the same way, because we use the def keyword to define other methods and as shown in the figure below, only for instances using one class, they can be used to define that instance method. Their functionality is not limited to accessing instance variables, they can do more as required.

#!/usr/bin/ruby -w

# define a class
class Box
  # constructor method
  def initialize(w,h)
   @width, @height = w, h
  end
  # instance method
  def getArea
   @width * @height
  end
end

# create an object
box = (10, 20)

# call instance methods
a = ()
puts "Area of the box is : #{a}"

When the above code is executed, it produces the following results:

Area of the box is : 200

Methods and variables of the class:

A class variable is a variable, which is shared between all instances of a class. This variable is an instance, which is an accessible object instance. Two @ character class variables are prefixed (@@). The class variables in the class must be initialized as shown below.

The definition of a class method is used: def () ends with the end character, which will be called the use class name, as shown in the following example:

#!/usr/bin/ruby -w

class Box
  # Initialize our class variables
  @@count = 0
  def initialize(w,h)
   # assign instance avriables
   @width, @height = w, h

   @@count += 1
  end

  def ()
   puts "Box count is : #@@count"
  end
end

# create two object
box1 = (10, 20)
box2 = (30, 100)

# call class method to print box count
()

When the above code is executed, it produces the following results:

Box count is : 2

to_s method:

An instance of any class defined should have a to_s method that returns a string representing object. Here is a simple example to represent a Box object in terms of width and height:

#!/usr/bin/ruby -w

class Box
  # constructor method
  def initialize(w,h)
   @width, @height = w, h
  end
  # define to_s method
  def to_s
   "(w:#@width,h:#@height)" # string formatting of the object.
  end
end

# create an object
box = (10, 20)

# to_s method will be called in reference of string automatically.
puts "String representation of box is : #{box}"

When the above code is executed, it produces the following results:

String representation of box is : (w:10,h:20)

Access Control:

Ruby provides three levels of protection instance methods: public, private and protected. Ruby does not have any access control for application instances and class variables.

  1. Public Methods: Anyone can be called a public method. The method defaults to public initialization, except for private. .
  2. Private Methods: The private method cannot be accessed, or even browsed from outside the class. Only class methods can access private members.
  3. Protected Methods: Protected methods can be called, only by defining objects of the class and its subclasses. Access is saved inside the class.

Here is a simple example to illustrate the syntax of three access modifiers:

#!/usr/bin/ruby -w

# define a class
class Box
  # constructor method
  def initialize(w,h)
   @width, @height = w, h
  end

  # instance method by default it is public
  def getArea
   getWidth() * getHeight
  end

  # define private accessor methods
  def getWidth
   @width
  end
  def getHeight
   @height
  end
  # make them private
  private :getWidth, :getHeight

  # instance method to print area
  def printArea
   @area = getWidth() * getHeight
   puts "Big box area is : #@area"
  end
  # make it protected
  protected :printArea
end

# create an object
box = (10, 20)

# call instance methods
a = ()
puts "Area of the box is : #{a}"

# try to call protected or methods
()

When the above code is executed, the following result is generated. Here, the first method is called successfully, but the second method gives a prompt.

Area of the box is : 200
:42: protected method `printArea' called for #
<Box:0xb7f11280 @height=20, @width=10> (NoMethodError)

Inheritance of class:

One of the most important concepts in object-oriented programming is inheritance. Inheritance allows us to define a class in another class's project, which makes it easier to create and maintain applications.

Inheritance also provides an opportunity to reuse the functionality of the code and fast implementation time, but unfortunately Ruby does not support multi-level inheritance, but Ruby supports mixing in. A mixin inherits multiple inheritances, and only the interface part is like a special implementation.

When creating a class instead of writing new data members and member functions, the programmer can specify that the new class inherits members of the existing class. This kind of existing class is called a base class or a parent class and a new class is called a derived class or a subclass.

Ruby also supports inheritance. Inheritance and the following examples explain this concept. The syntax of an extension class is simple. Just add a < character to the name of the superclass declaration. For example, classBigBox, a subclass of the Box class:

#!/usr/bin/ruby -w

# define a class
class Box
  # constructor method
  def initialize(w,h)
   @width, @height = w, h
  end
  # instance method
  def getArea
   @width * @height
  end
end

# define a subclass
class BigBox < Box

  # add a new instance method
  def printArea
   @area = @width * @height
   puts "Big box area is : #@area"
  end
end

# create an object
box = (10, 20)

# print the area
()

When the above code is executed, it produces the following results:

Big box area is : 200

Method overloading:

Although new functions can be added in derived classes, sometimes the behavior you want to change is already defined in the method in the parent class. Just keep the same method name and rewrite the function of the method as shown in the following figure, in this example you can do this:

#!/usr/bin/ruby -w

# define a class
class Box
  # constructor method
  def initialize(w,h)
   @width, @height = w, h
  end
  # instance method
  def getArea
   @width * @height
  end
end

# define a subclass
class BigBox < Box

  # change existing getArea method as follows
  def getArea
   @area = @width * @height
   puts "Big box area is : #@area"
  end
end

# create an object
box = (10, 20)

# print the area using overriden method.
()

Operator overloading:

We want the "+" operator to use +, and the * operation is multiplied by a scalar by a box's width and height. Here is the definition of a Box class and the mathematical operator:

class Box
 def initialize(w,h) # Initialize the width and height
  @width,@height = w, h
 end

 def +(other)     # Define + to do vector addition
  (@width + , @height + )
 end

 def -@        # Define unary minus to negate width and height
  (-@width, -@height)
 end

 def *(scalar)    # To perform scalar multiplication
  (@width*scalar, @height*scalar)
 end
end

Freeze object:

Sometimes, we need to prevent the changed objects. The freezing method allows us to do this, effectively bringing an object to a constant. Any object can be frozen by calling. No modification of frozen object: Its instance variable cannot be changed.

Can it be used? Statement checks whether a given object has been frozen. In the case of frozen object statement method returns true, otherwise returns false value. The following example of freeze concept:

#!/usr/bin/ruby -w

# define a class
class Box
  # constructor method
  def initialize(w,h)
   @width, @height = w, h
  end

  # accessor methods
  def getWidth
   @width
  end
  def getHeight
   @height
  end

  # setter methods
  def setWidth=(value)
   @width = value
  end
  def setHeight=(value)
   @height = value
  end
end

# create an object
box = (10, 20)

# let us freez this object

if( ? )
  puts "Box object is frozen object"
else
  puts "Box object is normal object"
end

# now try using setter methods
 = 30
 = 50

# use accessor methods
x = ()
y = ()

puts "Width of the box is : #{x}"
puts "Height of the box is : #{y}"

When the above code is executed, it produces the following results:

Box object is frozen object
:20:in `setWidth=': can't modify frozen object (TypeError)
    from :39

Class constants:

You can define a direct number or string value in a class without defining a variable as @@ or @. By specification, we keep the constant name capitalization.

Once a constant is defined, it cannot change its value, but it can be accessed directly in a class like a constant. However, if you want to access a constant outside of a class, then you need to use the class name::const, as shown in the following example.

#!/usr/bin/ruby -w

# define a class
class Box
  BOX_COMPANY = "TATA Inc"
  BOXWEIGHT = 10
  # constructor method
  def initialize(w,h)
   @width, @height = w, h
  end
  # instance method
  def getArea
   @width * @height
  end
end

# create an object
box = (10, 20)

# call instance methods
a = ()
puts "Area of the box is : #{a}"
puts Box::BOX_COMPANY
puts "Box weight is: #{Box::BOXWEIGHT}"

When the above code is executed, it produces the following results:

Area of the box is : 200
TATA Inc
Box weight is: 10

Class constant inheritance is like instance methods and can be overridden.
Create an object using assignment:

When an object is created without calling its constructor initialization, there may be a situation where the new method can be used, in which case the allocation can be called, which will create an uninitialized object, see the following example:

#!/usr/bin/ruby -w

# define a class
class Box
  attr_accessor :width, :height

  # constructor method
  def initialize(w,h)
   @width, @height = w, h
  end

  # instance method
  def getArea
   @width * @height
  end
end

# create an object using new
box1 = (10, 20)

# create another object using allocate
box2 = 

# call instance method using box1
a = ()
puts "Area of the box is : #{a}"

# call instance method using box2
a = ()
puts "Area of the box is : #{a}"

When the above code is executed, it produces the following results:

Area of the box is : 200
:14: warning: instance variable @width not initialized
:14: warning: instance variable @height not initialized
:14:in `getArea': undefined method `*' 
  for nil:NilClass (NoMethodError) from :29

Class information:

If the class defines executable code, it means that they are in the context of execution some objects: something that they must refer to. Let's see what it is.

#!/usr/bin/ruby -w

class Box
  # print class information
  puts "Type of self = #{}"
  puts "Name of self = #{}"
end

When the above code is executed, it produces the following results:

Type of self = Class
Name of self = Box

This means that a class is defined as the class of the current object and executed. Methods in metaclasses and their superclasses will be defined in the process of execution.