OOP: Classes & Objects

💎 Ruby Lesson 10 Intermediate

Ruby is purely object-oriented: everything, including integers and string values, is an object. Classes act as templates to instantiate objects.

1 Instantiation and the initialize method

Classes in Ruby encapsulate states and behaviors. Objects are created using the `new` constructor method, which automatically invokes the class's **`initialize`** method, acting as the constructor.

2 Classes Code

Let's run a program declaring classes and instantiating objects:

Ruby — Classes & Objects ▶ Run Code
class Student
  # Constructor method
  def initialize(name, age)
    @name = name # Instance variables start with '@'
    @age = age
  end

  def print_details
    puts "Student: #{@name}, Age: #{@age}"
  end
end

# Instantiate using new
s1 = Student.new("Alice", 21)
s1.print_details
3 Code Challenge
Challenge: Write a class named `Car` with an constructor that accepts `brand` and `year`. Expose a method called `drive` that prints a message indicating the car is driving.