Class Inheritance in Ruby

Ruby is an object oriented programming language and as such it supports class inheritance out of the box. In order to utilize class inheritance in Ruby, you need to create a subclass of the original class. The subclass overrides its parent methods and may add new methods as needed.

class MySubclass < String
 def mixing
  split(//).sort_by {rand}.join
 end
 def inspect
   mixing.inspect
 end
end

It is interesting to note though that Ruby developers in general don’t use subclasses and often times modify classes directly by adding methods to the classes defined in Ruby. Rails framework is one of such libraries that directly adds methods to core Ruby classes. There are dangerous with this approach. For instance, new method that you adding to a Class may have existing method already defined prior, so your method will simply override default method with unexpected consequences.

In general, if you think that your method will only be applied to an instance of the class, then create a subclass. If you think, you can create better version of existing method in the class, then use override method to gain efficiency. 

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…