Ruby’s philosophy behind duck typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fundamental approach to ruby objects should take into account not the classes which objects are derived form but rather methods that define the object.

Here is an example of checking an object to see whether it is a string like.

“My string”.respond_to? :to_str  /* returns true
4.respond_to? :to_str /* returns false

Calling on obj.is_a? String tells us that object is derived from the String class but it will not catch other object types not instantiated from String class even though they are intended to be strings. Exception messages is one such example when string representing an exception is derived from Exception class and check for string.is_a? won’t produce expected result. In order to correctly determine whether certain method is of certain type, you need to use .respond_to? Versus .is_a? This is duck typing in it basic form.

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…