Roshan Book

My Tech Notebook

Learning Ruby Part 3 – Inheritance

Inheritance is simply copying all the attributes from a base class to new class. It will save you lots of typing.


class Animal

attr_accessor :name, :age , :trait


This is how we declare a base class

class Dog < Animal


And this is how Dog class copies attributes from base class Animal. Now Dog has same attributes as Animal.

Adding Additional Attributes

Suppose you want to add extra attribute called type, declare Dog class like below

class Dog < Animal

attr_accessor :type


And now we have added attribute to Dog class, which is not in Base class “Animal”



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: