0
0
Rubyprogramming~15 mins

Accessing parent methods in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Accessing parent methods
📖 Scenario: Imagine you are creating a simple program to manage animals. You want to show how a child class can use a method from its parent class.
🎯 Goal: You will create a parent class with a method, then a child class that calls the parent's method using super. Finally, you will print the result.
📋 What You'll Learn
Create a parent class called Animal with a method sound that returns the string "Some sound".
Create a child class called Dog that inherits from Animal.
In the Dog class, create a method sound that calls the parent sound method using super and adds " and Bark" to the returned string.
Create an instance of Dog and print the result of calling its sound method.
💡 Why This Matters
🌍 Real World
In real programs, child classes often need to use or extend the behavior of their parent classes. This helps keep code organized and avoids repetition.
💼 Career
Understanding how to access parent methods is important for software developers working with object-oriented languages like Ruby, as it is a common pattern in many applications.
Progress0 / 4 steps
1
Create the parent class
Create a class called Animal with a method sound that returns the string "Some sound".
Ruby
Need a hint?

Use class Animal to start the class and def sound to define the method.

2
Create the child class
Create a class called Dog that inherits from Animal. Inside it, define a method sound that calls super and adds " and Bark" to the returned string.
Ruby
Need a hint?

Use class Dog < Animal to inherit. Use super inside sound to call the parent method.

3
Create an instance of Dog
Create a variable called dog and set it to a new instance of the Dog class.
Ruby
Need a hint?

Use dog = Dog.new to create the instance.

4
Print the dog's sound
Write a puts statement to print the result of calling the sound method on the dog instance.
Ruby
Need a hint?

Use puts dog.sound to print the sound.