Ruby for Programmers – Part 8: Stay Classy

In a language where everything is an object, then being able to create your own custom objects is a very powerful tool. Thus the below example:

And like any good OOP language, you can has inheritance:

On creation, it uses the #initialize function, rather than new. Note that it doesn’t matter what initialize returns, created an object via #new always returns the created object.

As an object, it’s main purpose is to hold data and to process it. Using the special “@” before a variable means to access an instance variable. Check this example:

@hp is an internal variable accessible within the instanced object. Unless you create a method for it, you cannot access that data from outside the object. (Well, I lied see below, but it’s really for debugging and not recommended for normal use:)

Combined, you can do some crazy things:

For the Animal, it works like normal. For the Dog, it’s hp is nil because the initialize step was overwritten and instead did not define the @hp. For the Cat, it returns an error because it requires the breed. The LolCat works because it provides the breed, runs the super function (which runs the function of it’s immediate ancestor class), and uses the #show_hp function from the super ancestor Animal.