Welcome to day 27 of the 49 Days of Ruby! 🎉
Today is all about taking a lot of what we have learned so far and bringing it together.
In the past lessons, we learned about some of the critical applications of Object-Oriented programming, like classes and instantiations. We have yet to speak specifically about what Object-Oriented programming (OOP) is. Let's take today to do that.
What is Object-Oriented Programming?
Ruby is one of the best languages to learn OOP in because Ruby was built for OOP!
Remember all those classes of Coffee
we built in so many of the previous lessons? Did we ever stop to think about why we were building a Coffee
class to begin with?
Perhaps we are creating a coffee shop made out of code. In this programmatic coffee shop, we will have coffee, milk, tables, chairs, cash registers, and a whole lot more.
Each specific type of thing should only really know about itself. We want to encapsulate all the logic for coffee inside coffee so that a chair doesn't need to worry about the quality of the beans.
Encapsulation is a crucial concept in OOP. It is just as we stated above. We put things in classes so to separate out the distinct pieces of code from each other. Coffee goes in a coffee class, chairs go in a chair class, etc., etc.
Another important concept in OOP is inheritance. If you recall we had a lesson earlier on inheritance. It is the idea that all objects descend from earlier objects, and likewise, are the ancestors of further objects down the inheritance line.
Inheritance is important because we want to keep things organized, among other reasons. I have some code functionality in Class A that will be shared with Class B. Do I copy and paste all that code from A into B? No, rather let Class B inherit what is in Class A, keeping it all tidy and neat.
One more good concept to know about OOP is something called polymorphism. What is this word that sounds like it comes from a philosophy class?
It's the idea that it can take many shapes. Specifically, for us, it means that while I have a generic Coffee
class, I can create another class called Americano
that has its own unique traits while also inheriting the more broad traits from Coffee
:
class Coffee
def brew
puts "Making a coffee now..."
end
end
class Americano < Coffee
def brew
puts "Making an Americano now..."
end
end
I hope this gave some more context to all of our earlier discussions of the practice of Object-Oriented programming. See you tomorrow!
Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.
Top comments (0)