Objects and Classes in Ruby

Ruby is an object orient language as such it supports the following important object oriented concepts as classes, polymorphism, and inheritance. There are other object oriented concepts that are found in Ruby only. For example, Ruby allows for Duck Typing meaning that you don’t need to define a datatype of the object. Ruby is smart enough to figure it out based on object methods. “If it quacks like a duck it is a duck.” hence “Duck Typing”

You can see how two methods are defined in Ruby in order to appreciate simplicity of the Ruby Duck Typing below

def do_something(MyObject obj)
  obj.do_one_thing
end

vs

def do_something(obj)
  obj.do_one_thing
end

We can see that in our first method implementation we can only pass objects of type MyObject and any other object type will fail with the message “TypeException: object is not of type MyObject”. However, second method implementation will allows us to pass different objects as long as all object that we pass have do_one_thing implemented. Method do_something will not prevent you from passing multiple object types and Ruby is smart enough to figure out what object method to call and execute.

do_something(MyObject.new)
do_something(YourObject.new)

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…