Classes and Objects in Ruby Language
Ruby is a dynamic and object-oriented programming language known for its simplicity and elegance. At the heart
of Ruby’s object-oriented design lies the concept of classes and objects. In this post, we will explore what classes and objects are in Ruby and how they are used in real-world scenarios.Classes in Ruby
In Ruby, a class is like a blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) that the objects will have. Let’s look at an example of defining a simple class in Ruby:
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def introduce
puts "Hi, my name is #{@name, and I'm #{@age} years old."
end
end
In this example, we have defined a Person
class with two attributes (name and age) and a method (introduce
) that allows a person object to introduce themselves.
Objects in Ruby
Once you have defined a class, you can create objects (also known as instances) of that class. Objects are individual instances of the class, each with its own unique set of attributes and state. Here’s how you can create and use objects of the Person
class:
person1 = Person.new("Alice", 30)
person2 = Person.new("Bob", 25)
person1.introduce
person2.introduce
In this code, we create two Person
objects, person1
and person2
, with different name and age attributes. We then call the introduce
method on each object to have them introduce themselves.
Inheritance in Ruby
Ruby supports inheritance, allowing you to create new classes based on existing ones. This promotes code reuse and modularity. For example, you can create a Student
class that inherits from the Person
class:
class Student < Person
attr_accessor :student_id
def initialize(name, age, student_id)
super(name, age)
@student_id = student_id
end
def study
puts "Studying hard with student ID: #{@student_id}"
end
end
The Student
class inherits the attributes and methods from the Person
class and adds its own unique attributes and methods.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.