Page Content

Tutorials

Objects And Classes In Ruby Practical Object-Oriented Design

Objects And Classes in Ruby

Object-Oriented Programming (OOP) relies heavily on the ideas of objects and classes, especially in languages like Ruby where almost everything you work with acts like an object.

Objects

One of Ruby’s basic data structures is an object. All values, including nil, true, false, and basic numeric literals, are objects in Ruby. That’s just any piece of data. Like the number 3 or the string ‘hello’.

There are three things an object can do:

Hold State (Data): Data, sometimes referred to as instance variables, can be contained in an object together with references to other objects.

Receive Messages (Methods): Methods (functions) that have unique access to an object’s data can be found inside of it. Sending an object a message is a common term used to describe calling a method on the object.

Send Messages: Other methods or functions can be called or executed by an object’s methods.

Assigning a value to a variable (s = "Ruby") only stores a reference to the object in the variable; it does not actually copy the object into the variable.

Classes

For objects, a class acts as a template or category. The internal state (instance variables) of an object is altered via a group of linked methods. Classes in Ruby are first-class objects each is an instance of class Class . Typically, you create a new class by using: class Name # some code describing the class behavior end. When a new class is created, an object of type Class is initialized and assigned to a global constant ( Name in this case).

Ruby requires that class names begin with a capital letter and are constants. It is possible to organize classes in a hierarchy, where each class either directly or indirectly derives from the root class, the Object class.

Object behavior is defined by classes:

Encapsulation: Ruby enforces rigorous encapsulation, meaning that only defined accessor methods from outside the object can access the state of an object (instance variables).

Instantiation: Instantiation is the process by which a particular object is created using a class declaration. A class instance is called an object.

Creating Objects and Initialization ()

Usually, executing the class method new creates new object instances. This method automatically calls the specific instance method called initialize after allocating memory for the object. As the constructor for the class, the initialize method establishes the initial state of the object.

Arguments passed to new are passed straight to initialize.

Code Example: Defining a Class and Initializing Objects

The class keyword is used to define a class in the Ruby language. To define instance variables, prefix the variable name with the at sign (@), as in @name.

Now let’s create a class. A cat with a name attached:

class Cat
  # This is the constructor method, automatically invoked by .new
  def initialize(name)
    @name = name # @name is an instance variable
  end

  # Instance method to define the cat's behavior
  def speak
    puts "I'm #{@name} and I'm 2 years old"
  end
end

# Creating instances (objects) of the Cat class
new_cat = Cat.new("garfield") 
# => <Cat:0x... @name="garfield">

new_cat.speak

Output

I'm garfield and I'm 2 years old

The class definition, initialize, and instance methods are covered in the code snippets.

Accessing Object Data (Accessors)

The object’s instance variables are internal and not readily accessible from the outside. Accessor methods (getters and setters) must be defined by classes in order to permit external access.

Define an accessor method (a “getter”) that merely returns the value of the instance variable. This is the usual Ruby way for establishing readable instance variables.

Accessor Methods as an Example of Code

You can either build an accessor method by hand or automatically define a getter method with Ruby’s built-in conveniences, such as attr_reader.

Expanding upon the earlier example, we construct a class Point to represent coordinates and offer ways to get its state:

class Point
  # attr_reader automatically defines the getter methods for @x and @y
  attr_reader :x, :y 

  def initialize(x, y)
    @x, @y = x, y # Parallel assignment saves parameters into instance variables 
  end
  
  # Manual definition of a setter method (if you want to make the object mutable):
  def x=(new_x)
    @x = new_x
  end
end

# Instantiating the object
p = Point.new(1, 2)

# Accessing the instance data using the automatically defined getter methods:
q = Point.new(p.x * 2, p.y * 3) 
# p.x returns the value of @x (1); p.y returns the value of @y (2) 

puts q.x 

Output

2

Based on sections that describe the Point class example, instance variables that start with @, and accessors.

You can also read What Is Mean By Yield Keyword In Ruby With Code Examples

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index