Object Oriented Programming (OOP) in Ruby
Object Oriented Programming (OOP) is a programming paradigm that organizes code around objects. An object represents an entity in the real world or system being modeled.
Classes: Link to heading
- Classes are templates that define the attributes (instance variables) and behavior (methods) of objects.
- It is declared using the class keyword.
Example: Link to heading
Long way Link to heading
class Person
# Constructor
def initialize(name, age)
@name = name
@age = age
end
# Getters
def name
@name
end
def age
@age
end
# Setters
def name=(name)
@name = name
self
end
def age=(age)
@age = age
self
end
# ... other methods of behavior
end
Short form Link to heading
class Person
# class methods
def self.suggested_names
["john", "ana", "maria"]
end
# Constructor
def initialize(name, age)
@name = name
@age = age
end
# Instance methods(Getters y Setters)
attr_accessor :name, :age
# ... other methods of behavior
end
Even shorter shape Link to heading
class Person < Struct.new(:name, :age)
# Struct declares the constructor, getters and setters
# ... other methods of behavior
end
Each approach has its advantages and disadvantages. The long form offers more control, while the short forms are more concise. The choice depends on the specific needs of the class.
Objects: Link to heading
- The instances of a class are the objects.
- They are created using the new method of the class.
- Each object has its own values for the attributes defined in the class.
Example: Link to heading
person = Person.new("Juan", 25)
puts person.name # "Juan"
puts person.age # 25
Methods: Link to heading
- Methods are functions defined within a class that operate on the objects of that class.
- They can access and modify the attributes of the object.
- Class methods and instance methods can be defined.
Example: Link to heading
class Person
# ...
def greet
puts "hello, my name is #{@name}"
end
end
person.greet # "hello, my name is Juan"
Inheritance: Link to heading
- A class can inherit attributes and behavior from another class (parent class).
- The child class (subclass) can add its own functionality or modify the inherited one.
Abstraction: Link to heading
- OOP allows you to hide the implementation details of an object and expose only its interface (public methods).
OPO provides a way to organize code in a modular, reusable and maintainable way. By modeling the real world with objects, programs become easier to understand, modify, and extend.
Additional Tips: Link to heading
- You can use modules to group shared functionality between classes.
- You can use the MVC design pattern to separate business, presentation and control logic.
- You can use dependency injection to improve the testability and maintainability of the code.
Keep experimenting with OOP to create complex, well-designed applications!