e x p r e s s i c a

ruby on rails, business and technicalities

No public Twitter messages.

  • RSS
  • Facebook
  • Twitter
  • Linkedin

Ruby is DuckTyped

NOTE : This post may contains repeated and boring stuff for those who already have the programming practice of DuckTyping.

What is Duck Typing ?
Duck Typing is Dynamic Typing
In ruby we do not declare the type of the variable. It automatically becomes the object of the related class. For example, if we assign str = “hello string” then the variable str will automatically becomes the object of class String, that we can confirm by issuing str.class. But according to Duck Typing philosophy even Classes are not Types.
That is the basic rule of Duck Typing is that THE TYPE OF OBJECT IS DETERMINED BY WHAT IT CAN DO, NOT BY ITS CLASS. Lets exemplify the statement…
[source:ruby]
obj = nil

[/source]
now here the object obj is a NilClass object but (in ruby) it will be wrong to say that obj is a NilClass type object. The statement is confining the tasks that can be performed by it. Coz we can have the object obj as a NilClass object and still performing singleton functionalities declared over it. Like …
[source:ruby]
obj = (def wish; puts “good morning, lets code like a Duck :) ”; end)
obj # => nil
obj.class # => NilClass
obj.wish # => good morning, lets code like a Duck :)
[/source]

So, even a nil object can wish you good morning! Here a method wish has been added to a nil object. But it will not be available for all nil objects, or will that be ? Well, thats a homewok for you!!
Check this out, in this case the wish method will be available for all the nil objects… and the reason is that all the nil objects actually points to a same preserved nil object in the ObjectSpace but not creates a new object everytime like in most cases. Well, i will discuss more deeply regarding the ObjectSpace very soon.

Moreover, extending the modules over an object both at run time and compile time is itself a functionality supporting the statement that Classes are not types and this is what Duck Typing is.

Why known as Duck Typing ?

Alex Martelli, a member of the Python Software Foundation , have given the name DuckTyping to this approach in reference with Duck Test … which says that When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.
So, if an object is behaving like string the it is string type object but not if only it have the class as String.

2 Responses so far.

  1. paddy3118 says:

    In Duck typing its not the type of an object that is determined by what can be done by the type; it is that “the objects giving correct functionality as parameters to a method are determined by what the method/method signatures of the parameter objects are, rather than what the object type is”.

    - Paddy.

  2. hurx says:

    Thx for this explanation. It cleared up some things in my mind.
    Live long ans prosper.

    hurx


Sponsors