Quack Quack

One of the popular aspects of Ruby is the concept of "Duck Typing". It's a powerful aspect of the language that, once understood and utilized, shows the uniqueness of the Ruby type system.

One example I like to use when demonstrating what duck typing is to demonstrate this pseudo Ruby-code:

int someFunction(blah)
{
  if(blah.class == String) return blah.to_i
  elsif(blah.class == CustomClass) return blah.convert_custom_class_to_int
  elsif(blah.class == AnotherClass) raise "Can't convert AnotherClass to int!"
}

The above code shows a (poor) implementation of trying to do certain actions based on the class of the object. But why? What happens if we create new custom classes - then we have to go back and update this function to handle them. What we create a new String based class that has all sorts of new funky features. This doesn't fit into this model very well, either. Why not just do this:


blah.to_i

That's it. Finish. Done. We don't care what the class of blah is. We simply call to_i on it. Guess what? If to_i isn't implemented, we get an exception. That's okay - all we need to do is handle it!

In Ruby, types are defined by the capabilities of the objects, not by the name of their class. When we say:

some_object << "foo"

We don't care what the class of some_object is. All it needs to do is be able to respond to the << message. Instead of trying to figure out if our class handles this message, instead we just see if << succeeded.

begin
  some_object << "foo"
  rescue NoMethodError
  puts "Can't append to some_object"
end

So much simpler. In general, if you find yourself asking an object for its class, you may be making a mistake (yeah, there are valid uses for this). Instead, though, you can ask an object if is responds to a certain method.

#Bad
if(a.class == Foo); then a.some_method
end

#Good
if(a.respond_to?(:some_method)); then a.some_method
end

Duck Typing. Very powerful stuff.

More info on Ruby's duck typing:

RubyGarden

Also on .NET

This feature also exists in Boo (which is a fun language). I know you weren't trying to start a list of "gotchas" here, but if you've never heard of Boo, give it a once over.

Of course, seeing how this looks in Ruby just gives me another reason to give struts dirty looks, I'm not sure if that's good or bad :)