On 12/15/05, Daniel Schierbeck <daniel.schierbeck / gmail.com> wrote:
>    class Kernel
>      def cast(obj, klass, method = nil)
>        return obj if obj.kind_of? klass
>
>        method = "to_#{method || klass.downcase}"
>
>        unless obj.respond_to? method
>          raise TypeError, "Can't convert #{obj.class} into #{klass}"
>        end
>
>        cast_obj = obj.send(method)
>
>        unless ccast_obj.kind_of? klass
>          raise TypeError, "#{obj.class}##{method} should return #{klass}"
>        end
>
>        return cast_obj
>      end
>    end

Like David said this is basically the opposite of duck-typing.  The
idea of duck-typing is that the code should completely ignore the type
(however you want to define it).  You just let ruby raise an exception
if the object doesn't respond to the methods you need from the
objects.

I've heard the misconception before that duck-typing is most useful
for type casting (i.e. #to_s method).  To me, that is just a
conveinence (the caller could just as easy have explicitly done the
conversion).  That is not where the power and beauty of duck-typing
lies.  It really is a quite flexible polymorphic concept.