One of the first things that I was told when I first started my dev journey was that in ruby, “everything is an object”, and “objects can send messages to each other”, what does that mean? This is a humble blurb, a tiny toe-dip into exploring what these concepts mean in an object oriented programming language like ruby.
To start, I wanted to refresh what object oriented programming is in comparison to functional programming. They’re referred as different paradigms for programming. Functional programming is declarative, utilizing functions for the computer to do what you want and not necessarily caring about how it achieves the result. It focuses on functions, avoids sharing state and mutable data.
OOP is imperative, where you explain the steps of how to get exactly what you want, focusing on classes and objects. The main pillars of OOP are: abstraction, encapsulation, inheritance and polymorphism. The two main properties are states (attributes) and behaviours (methods).
All objects are instances of a class, and if everything in ruby is an object… To get an instance when you have a class you call .new on it. You can check if anything is an object through using the .class method. Something like a string is an object of the String class:
Objects operate in a system called The Object Model, regardless of if they are strings, numbers, classes, modules, etc. All classes have a link to a superclass, and there are three special classes: Object, Module, Class. To show what any class inherits from, we can use the .ancestors method:
The BasicObject class is the superclass to rule all classes. To show this visually, this image taken from skilldrick.co.uk shows the links in a comprehensive way:
You can also check an object’s id with the object_id method and methods method as they are available to all objects!
When I googled about objects sending messages to other objects for this post, I was surprised to find that I’d had already been doing this. Sending a message or calling method in ruby is done through dot notation. This can be seen from the previous examples like when an object gets called with .class, .method. or .ancestors! I think it should also be noted that while objects can receive any message, whether or not the method that corresponds to it is correct or exists is another thing.
Ref: