Welcome to day 21 of the 49 Days of Ruby! 🎉
Welcome back to 49 days of Ruby! Today, on day 21, we're going to discuss an important concept in understanding how Ruby works. An understanding of this topic will help you when you are writing your code. What is this concept? It's called inheritance.
What is inheritance?
Inheritance in programming is very similar to the widely used definition of the word in the broader world. It is essentially the idea that something descends from something else, and as a result inherits part of the ancestor's attributes.
Imagine, a child and parent relationship. The child descends from the parent, and children usually share some attributes of their parents. This is true generationally. Grandparents, great-grandparents, great-great-grandparents, and on.
As a result, inheritance in code is the idea that something comes from something else and shares aspects of what it comes from.
Let's take a look at it in Ruby.
Inheritance in Ruby
What does inheritance in Ruby look like?
class Parent end class Child < Parent end
In the code example above we create a class called
Parent. This is the superclass*, or the parent class. After that, we create a class called
Child, which is the **subclass , or the child class.
Child class inherits from the
Parent class with the special key of
<. The direction of the carrot indicates the direction of the inheritance. In this case, the Parent is passing on its attributes to the Child.
As a result, let's say we had this kind of code:
class Parent def self.say_hello puts "Hi!" end end class Child < Parent end
Child class would have access to the
#say_hello method of the
> Child.say_hello # => "hi!"
In Ruby every class has an inheritance tree. This inheritance tree is the family tree for the class. You can trace it all the way back to the original class. What's the original class for an object in Ruby? If you guessed
Object you would be right!
Take a look at this example. In the example we ask what the
superclass is for the
> String.superclass # => Object
That's it for today! Come back tomorrow for day 22!
Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.
Latest comments (0)