Ruby Object-Oriented-Programming

Michael Horowitz
5 min readJul 12, 2020

--

Photo by Fotis Fotopoulos on Unsplash

What is an object according to Ruby? An object is a ‘thing’; it can be a real and tangible item that we use everyday or something more abstract, it does not really matter, as long as that ‘thing’ has attributes. Some examples of real-world (tangible) objects would be a person, book, or a plate. Examples of something more abstract would be a phone call or a text message.

How are these ‘things’ connected at all? The connection would be they all have attributes. A person would have a name, height, age, etc. But what about a phone call? Well, you could say the connection between the two or more phones involved is an attribute, or the duration of the call. Attributes of a text message could be the length of the text, when is was sent, and received. All of these are just attributes to your objects, and we give those objects in object-oriented-programming by, methods! Methods are the way to do everything in Ruby, and in general for OOP in order to organize everything.

Classes in object-oriented programming is the layout or blueprint of an object. What does that mean? So when creating a class all you are really doing is essentially laying out the foundation in which you create an instance. I like to imagine an assembly line in a big factory producing cars. The “blueprint” is created, and the methods are the pieces in the assemly line that help put together a car. Imagine you are planning to build a house. What does a house REQUIRE in order to exist? The basic necessities someone would want to have in their home. You could say at least one bedroom, bathroom, and kitchen right? So to build a class you are just building the outline of what it should be and then creating individuals from that blueprint. To create a class we need to start with the class keyword. As such:

class House # < — this the "blueprint" for anything you want!end

Now we can create the individuals that come out of the class and they are called “instances”. An instance is the outcome from the blueprint and is the actual object itself.

To create a new instance is as such:

new_house_for_brother = House.new#NOTE: you would probably want to call the variable something close to the actual name of whatever you are creating to help you remember :)

Now, how can we have our objects do something? This is with methods, a method is a command that you can reuse multiple times and it’s associated with a specific class. Let’s give an example of a dog, because dogs are the best!

class Dog  def bark
puts “Woof woof!”
end
end

Now this is a very simple example but you can do so much more; the only challenge is ensuring correct syntax. Now in order to call this method we must do as such:

dog = Dog.new # < — this is creating a dog instancedog.bark # < — this is that instance calling the bark method#NOTE: Notice how we call the method on the variable lowercased “dog” and not the class name “Dog”, this is because we are calling it on the instance because it is an instance method, not a class method.

What’s next? Well we have to also know how to store data with instance variables. We will stick with dogs and do so as such:

class Dog def initialize(name, breed)
@name = name
@breed = breed
end
end

Now I’m sure you are asking yourself what’s with the @? This is how we create instance variables. Why use instance variables? This is so that scope does not get in our way, the instance variable is available throughout the class. This method above, ‘initialized’ our dog with a name and a breed, the only way for this dog to exist it needs at least these two things. Now obviously a dog needs much more to exist, but for learning purposes let’s leave it as such. Basically what is happening here is we give it arguments of a name and a breed:

dog = Dog.newdog = Dog.new(“Frank”, “Golden Retriever”)

Through this we have our instance variable @name = “Frank" and @breed = “Golden Retriever”. But we are not quite finished. We also need methods for our dog to remember and to tell us what is his/her name.

These methods are called reader and writer methods.

For example our reader method for the name is:

def name  @nameend

This just returns whatever we set the value to when creating the dog, it is the same for breed, but instead of putting name just put in breed.

Example for writer method for our name is:

def name=(name)  @name = nameend

This method sets the value similar to what we did in initialize, but this saves the information for the instance to remember. The difference is, the initialize runs as soon as the dog instance is created, and these methods run after that, giving the instance the attribute values it was created with.

There are shortcuts to both of these methods, be advised though, if you want to use the shortcut then do NOT use the methods as well. These shortcuts are as follows:

attr_reader :name # < — this is in place of making the reader methodattr_writer :name # < — this is in place of making the writer method

Now there’s an even quicker shortcut. This shortcut makes both a reader and writer method for you:

attr_accessor :name #< — this does both attr_reader and attr_writer

Class methods are similar, but they have one key element that separates them from instance methods, and that is the selfkeyword. Now self can mean one of two things, either the class or the instance, it depends on where you use it. You must be very diligent on where you are using self, because if you use it wrong you could mess up the rest of your code. To use self for the class method you can do as such:

class Food def self.cook # < -self here is refering to the class
end
end

This is an example of a class method through the use of self. Why would we use class methods? We probably do not use class methods that often, like when using the Mathclass in Ruby, like when you want the square root of a number.

Math.sqrt(9)

Here we do not need a Math object because Math doesn’t store any data.

To use self as an instance you would have to use it in an instance method.

For example:

class Dog
@@all = []
def initialize
@name = name
@@all << self
# self here is the instance that is being created and we
# are just shoveling it into an array of all dogs
end
end

Now you may ask yourself what is @@? That is a class variable, we can use that class variable as an array, or a hash to store the instances created.

Basically what we did here was initialize a dog through the dog class and then we have the dog class store all of its instances in the @@all array.

These are just some of the basic set up pieces to start making classes and instances.

--

--

No responses yet