Blog

Filter posts by Category Or Tag of the Blog section!

Inheritance in Ruby

Wednesday, 18 January 2017

As I'm a beginner in Ruby, so don't expect me to write an advanced post about that. I'm writing for beginners like myself! I was just reading about inheritance in ruby. It is so funny! Look at the following class:

 

class Animal

  def speak

  "Hello from an animal!" 

  end

End

 

inheriting from a class is so easy in ruby as well:

 

Class Cat< Animal

End


 

That's it! Let's print the output:

 

myCat = Cat.new

puts myCat.speak

 

The output would be:  Hello from an animal!

There is a built-in function in Ruby called super which just like the base in C#.

 

class Dog < Animal

   def speak

 super + " And this is a Dog"

 end

End

 

 And if we would like to create an instance from Dog and print the output, it would be:

 

 

dog = Dog.new

Dog.speak

 

 

Output:  Hello from an animal! And this is a Dog

I learned the inheritance in my last 15 minutes! I will share more about this lovely programming language.

Category: Software

Tags: Ruby

comments powered by Disqus