While we are big fans of functional programming and you could see our material about Elixir from a Rubyist’s perspective… There is a room for love for OOP in our hearts! Ruby and Ruby on Rails are our main stack, and this is impossible not to pay attention to object-oriented programming and understand it. So, today we’re doing Object-Oriented Programming (OOP) with Ruby!
To start with, learning the main OOP principles will help you to reach better performance in Ruby.
Object-Oriented Programming is a programming technique that promotes code reuse by structuring code into modular components (called objects). It tries to solve the problem of spaghetti code (unstructured and difficult to maintain) by offering a simplified method of programming. Sounds so good!
Objects and classes
Languages that support object-oriented programming typically use inheritance for code reuse and extensibility in the form of either classes or prototypes. Those that use classes support two main concepts:
- Classes – the definitions for the data format and available procedures for a given type or class of object; may also contain data and procedures (known as class methods) themselves, i.e. classes contain the data members and member functions. To rephrase, a class is an easy way to create multiple objects of the same type. It’s like a template.
- Objects – instances of classes. An object is a way to structure your code. It contains two things: data (or properties) and logic(or methods). You can think about objects as self-contained pieces of functionality that can communicate with other objects via messages.
Main OOP concepts
- Encapsulation – a mechanism for hiding data from the outside of an object. It is a concept where data and methods that work on that data are bundled together in one unit.
- Inheritance – this concept permits code reusability by specifying common traits for different objects by defining a parent/child (or is-a) relationship.
- Polymorphism – methods can behave differently based on the type of object you are calling them on. You are able to send the same message to different objects and get back different data.
Read also about duck typing and find some examples of Ruby code here.
Recommended sources about OOP in Ruby
- Practical Object-Oriented Design in Ruby
- 99 Bottles of OOP
- Refactoring: Ruby Edition
- Metaprogramming Ruby
But remember, that you don’t need to start OOP first. Go coding, get more practice and then just recognize that you’re doing object-oriented programming. That is the most natural way to learn it. There are many great additional materials mentioned in our material Ruby books and tutorials.