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)