Object-Oriented Programming in Ruby
Ruby is a dynamic, object-oriented programming language known for its simplicity and flexibility. It was create
d in the mid-1990s by Yukihiro “Matz” Matsumoto and has gained popularity for its elegant syntax and powerful object-oriented features. In this post, we’ll explore the fundamentals of object-oriented programming (OOP) in Ruby with examples.Object-Oriented Concepts in Ruby
Ruby is a pure object-oriented language, which means that everything in Ruby is an object. Objects are instances of classes, and they can have attributes (data) and methods (functions). Here are some core OOP concepts in Ruby:
Classes
A class is a blueprint for creating objects. It defines the structure and behavior of objects. You can create a class in Ruby using the class
keyword.
class Person
def initialize(name, age)
@name = name
@age = age
end
end
Objects
An object is an instance of a class. You can create objects by calling the class’s constructor method new
.
person1 = Person.new("Alice", 30)
person2 = Person.new("Bob", 25)
Attributes
Attributes are instance variables that store data for objects. They are prefixed with the @
symbol.
class Person
def initialize(name, age)
@name = name
@age = age
end
end
person = Person.new("Charlie", 40)
puts person.instance_variable_get(:@name) # Accessing the name attribute
Methods
Methods are functions defined within a class. They 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
person = Person.new("Dave", 35)
person.introduce # Calling the introduce method
Inheritance
Inheritance allows one class to inherit attributes and methods from another class. Ruby supports single inheritance.
class Student < Person
def initialize(name, age, student_id)
super(name, age)
@student_id = student_id
end
end
Encapsulation, Polymorphism, and Abstraction
Ruby also supports encapsulation, polymorphism, and abstraction, which are key principles of OOP:
- Encapsulation is achieved through access control modifiers (
public
,private
, andprotected
) to restrict or allow access to methods and attributes. - Polymorphism is demonstrated when objects of different classes respond to the same method name.
- Abstraction is achieved by defining high-level interfaces or classes that hide the implementation details.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.