2 m read

Introduction to Classes and Objects in Ruby

Ruby heavily relies on the concepts of classes and objects. A class in Ruby serves as a blueprint for creating objects. It embodies distinct characteristics and functions.

For instance, a class Vehicle may encapsulate traits like color, size, and methods like speed_up and shut_down. Every Ruby class should commence with a capital letter.

Defining a Class

To define a class in Ruby, we make use of the keyword ‘class’ followed by the class name, and an ‘end’ keyword.

  class Vehicle
  end

Code language: Ruby (ruby)

Instantiating a Class

An object is an instance of a particular class, created using the 'new' method provided by Ruby’s library.

  my_car = Vehicle.new

Code language: Ruby (ruby)

Instance Variables

Ruby classes have instance variables, accessible across different methods for a specific instance or object. They are prefixed with '@' symbol.

  class Vehicle
    def price
      @price = 20000
    end
  end

Code language: Ruby (ruby)

Global Variables

Though not available across different classes, Ruby also has global variables, reusable anywhere in the program.

  class Vehicle
    def initialize
      @@no_of_customers = 100
    end
  end

Code language: Ruby (ruby)

Creating an Object

Using Ruby’s 'new' method, we can create object instances of a particular class.

  my_bike = Vehicle.new

Code language: Ruby (ruby)

Object Manipulation

Objects hold methods and data, and they interact via method calls. By changing an object’s data, we can alter its behavior. For example, if we set an 'accelerate' method on a 'Vehicle' object to increase speed, changing this method’s parameters alters the object’s behavior.

Object Inheritance

Objects share properties and behavior, defined by their class or subclasses.

Object’s Identity

Ruby provides an ‘object_id’ method, returning a unique ID for every object. The same objects share the same ID. This ID remains constant throughout the object’s lifetime in the running program.

Conclusion

Class and object concepts in Ruby provide a robust foundation for building advanced applications. A class serves as a blueprint for objects, containing shared properties and behaviors.

Understanding how to define, instantiate, and manipulate classes and objects opens a gateway to object-oriented programming in Ruby. Remember: every Ruby class name starts with a capital letter, and everything in Ruby is an object.

Please refer to our previous article on Ruby methods for further reading.

Benji

Leave a Reply