1. Computing

Ruby Annoyances: Variables Don't Have Type

By

To many programmers new to Ruby and dynamic languages in general, one annoyance or point of confusion is that variables don't have type. Values have type, of course. Strings are Strings, numbers are some type of Numeric, but variables themselves don't have type. What's going on here?

If you're a C or C++ programmer, it's all about type. You have to meticulously plan out what type all of your variables are, the call signatures of every function (the type of each parameter), the type of every member variable of every class, etc. It's so ingrained in the mindset of statically typed language programmers, that's it's a hard habit to break.

But it's not all that different, when you think about it. What is a type? In a language like C, a type implies a specific size of variable in memory, and a convention of what will be there. An int type, for example, is typically one double word (32-bits) and contains a signed integer. In Ruby, things aren't that much different. Size is irrelevant since objects are passed by reference, so you just don't need to worry about that. And instead of conventions governing what's inside a variable, there are conventions governing what types of messages a value will respond to.

For some, this is difficult to imagine at first. Being able to pass completely off the wall and just plain wrong parameters to a method seems outright dangerous. But such errors are detected quickly. How? In compiled languages, it's a compile-time error. In dynamic languages, it's a runtime error. If you pass a number where the program is expecting a string or a regular expression, that object won't respond to the right messages, and it'll raise an exception. Largely, the types of things caught by compile-time errors are caught by test driven development.

This opens up a whole new can of worms though: duck typing. To a C programmer, this will seem very odd indeed. With duck typing, you can pass any object that responds to the right messages, whether that object was the type of object the method was expecting or not! Instead of a string, I might pass an object that builds strings dynamically, that responds to all of the same messages as a string.

To a new Ruby programmer, these can be annoyances. But they're not, they're just so utterly different, you need to give it some time. You'll wrap your brain around dynamic typing eventually, just give it time.

©2014 About.com. All rights reserved.