Ruby Classes And Objects

Ruby is an object-oriented language, which means it uses objects in programming. Objects are created using classes, which are the blueprint for objects.

Let's start with a basic introduction to classes and objects in Ruby.

1. Creating a Class

You can create a class in Ruby using the class keyword. Here's a simple example:

class Car
end

This creates a new class named Car. By convention, class names in Ruby are written in CamelCase.

2. Creating an Object

You can create an object, or an instance of a class, using the new method:

class Car
end

my_car = Car.new

This creates a new Car object and assigns it to the variable my_car.

3. Instance Variables

Instance variables are variables that belong to an instance of a class. You can use instance variables to keep track of information about each object. In Ruby, instance variable names start with an @ symbol:

class Car
  def set_color(color)
    @color = color
  end

  def get_color
    @color
  end
end

my_car = Car.new
my_car.set_color("red")
puts my_car.get_color  # outputs "red"

In this example, @color is an instance variable. Each Car object can have its own @color.

4. Constructors

A constructor is a special method that gets called when you create a new object. In Ruby, the constructor method is named initialize:

class Car
  def initialize(color)
    @color = color
  end

  def get_color
    @color
  end
end

my_car = Car.new("red")
puts my_car.get_color  # outputs "red"

In this example, initialize is a constructor that takes one parameter, color, and assigns it to @color.

5. Accessors

Ruby provides a convenient way to create getter and setter methods with the attr_accessor keyword:

class Car
  attr_accessor :color
end

my_car = Car.new
my_car.color = "red"
puts my_car.color  # outputs "red"

In this example, attr_accessor :color automatically creates a getter method (color) and a setter method (color=) for @color.

This is a basic introduction to classes and objects in Ruby. There's a lot more to learn, including inheritance, modules, and more, but this should give you a good start.

  1. Creating classes and objects in Ruby:

    • Description: Classes are blueprints for creating objects, and objects are instances of a class.
    • Code example:
      # Class definition
      class Person
        # Constructor method
        def initialize(name, age)
          @name = name
          @age = age
        end
      
        # Instance method
        def display_info
          puts "Name: #{@name}, Age: #{@age}"
        end
      end
      
      # Object instantiation
      person1 = Person.new("John", 25)
      
      # Calling an instance method
      person1.display_info
      
  2. Class methods and instance methods in Ruby:

    • Description: Class methods are defined on the class itself, while instance methods operate on instances of the class.
    • Code example:
      class MathOperations
        # Class method
        def self.square(number)
          number * number
        end
      
        # Instance method
        def add(a, b)
          a + b
        end
      end
      
      # Using class method
      result = MathOperations.square(5)
      
      # Using instance method
      calculator = MathOperations.new
      sum = calculator.add(3, 4)
      
  3. Instance variables and class variables in Ruby:

    • Description: Instance variables are associated with instances of a class, while class variables are shared among all instances.
    • Code example:
      class Counter
        # Class variable
        @@count = 0
      
        # Constructor method
        def initialize
          # Instance variable
          @increment = 1
        end
      
        # Instance method using instance and class variables
        def increment_count
          @@count += @increment
        end
      
        # Class method accessing class variable
        def self.get_count
          @@count
        end
      end
      
      # Object instantiation
      counter1 = Counter.new
      counter2 = Counter.new
      
      # Using instance method
      counter1.increment_count
      counter2.increment_count
      
      # Using class method
      total_count = Counter.get_count
      
  4. Inheritance and polymorphism in Ruby classes:

    • Description: Inheritance allows a class to inherit attributes and methods from another class. Polymorphism allows objects of different classes to be treated as objects of a common base class.
    • Code example:
      # Base class
      class Animal
        def speak
          puts "Animal speaks"
        end
      end
      
      # Derived class inheriting from the base class
      class Dog < Animal
        def speak
          puts "Dog barks"
        end
      end
      
      # Polymorphism
      def animal_sound(animal)
        animal.speak
      end
      
      # Object instantiation
      animal = Animal.new
      dog = Dog.new
      
      # Polymorphic method call
      animal_sound(animal)
      animal_sound(dog)
      
  5. Encapsulation in Ruby classes and objects:

    • Description: Encapsulation restricts access to certain components of an object, enforcing data hiding and modularity.
    • Code example:
      class BankAccount
        # Encapsulation with private and protected methods
        def initialize(balance)
          @balance = balance
        end
      
        def deposit(amount)
          validate_positive(amount)
          @balance += amount
        end
      
        def withdraw(amount)
          validate_positive(amount)
          validate_sufficient_funds(amount)
          @balance -= amount
        end
      
        private
      
        def validate_positive(value)
          raise "Amount must be positive" unless value.positive?
        end
      
        def validate_sufficient_funds(amount)
          raise "Insufficient funds" unless amount <= @balance
        end
      end
      
  6. Ruby constructor and destructor methods:

    • Description: Constructors (initialize method) are called when an object is created. Ruby doesn't have explicit destructors, but there are methods like finalize that can be used for cleanup.
    • Code example:
      class MyClass
        # Constructor (initialize method)
        def initialize
          puts "Object initialized"
        end
      
        # Finalize method for "destructor" behavior
        def finalize
          puts "Object finalized"
        end
      end
      
      # Object instantiation
      obj = MyClass.new
      
      # Object destruction (not explicit, just for illustration)
      obj.finalize
      
  7. Ruby class initialization and instantiation:

    • Description: Initialization involves setting up an object's initial state when it's created. In Ruby, this is done in the initialize method.
    • Code example:
      class Book
        # Initialization method
        def initialize(title, author)
          @title = title
          @author = author
        end
      
        # Other methods can be added to the class
        def display_info
          puts "Title: #{@title}, Author: #{@author}"
        end
      end
      
      # Object instantiation with initialization
      book1 = Book.new("Ruby Programming", "John Doe")
      
      # Using other methods
      book1.display_info