In Ruby, classes are fundamental to object-oriented programming. They serve as blueprints for creating objects, encapsulating data and behavior into reusable units. Understanding classes is crucial for writing efficient and maintainable Ruby code.
To define a class in Ruby, use the class
keyword followed by the class name in CamelCase:
class Person
# Class definition goes here
end
Classes can have instance variables and methods. Instance variables are prefixed with @
and are unique to each object. Methods define the behavior of objects:
class Person
def initialize(name, age)
@name = name
@age = age
end
def introduce
puts "Hi, I'm #{@name} and I'm #{@age} years old."
end
end
To create an object (instance) of a class, use the new
method:
person = Person.new("Alice", 30)
person.introduce # Output: Hi, I'm Alice and I'm 30 years old.
To access and modify instance variables, you can use accessor methods. Ruby provides shortcuts for creating these methods:
class Person
attr_reader :name # Generates a getter method for @name
attr_writer :age # Generates a setter method for @age
attr_accessor :email # Generates both getter and setter methods for @email
end
For more information on getter and setter methods, check out Ruby Getters and Setters.
Class variables (prefixed with @@
) and class methods are shared across all instances of a class:
class Person
@@count = 0
def initialize(name)
@name = name
@@count += 1
end
def self.count
@@count
end
end
person1 = Person.new("Bob")
person2 = Person.new("Charlie")
puts Person.count # Output: 2
To learn more about class variables, visit Ruby Class Variables.
Ruby supports single inheritance, allowing classes to inherit behavior from a parent class:
class Employee < Person
def initialize(name, age, position)
super(name, age)
@position = position
end
end
For a deeper dive into inheritance, check out Ruby Inheritance.
Classes are essential in Ruby for creating organized, reusable, and maintainable code. They form the foundation of object-oriented programming in Ruby, allowing developers to model real-world concepts and relationships effectively. As you continue your Ruby journey, mastering classes will significantly enhance your ability to create robust and scalable applications.