f you're a C++ developer who's curious about all of the hype surrounding the Ruby programming language, this article is for you. It provides a high-level overview of the key differences between C++ and Ruby, and then presents a small, complete example application implemented with each language.
Be forewarned, however: learning Ruby can be a very frustrating experience! Because once you become familiar with this powerfully concise language, you might find returning to C++ a bitter pill to swallow.
A High-Level Language Comparison and a Running Example
C++ is a statically typed, compiled language that has hybrid object orientation. Its static typing means that the type of every expression and variable is known at compile-time, allowing significant correctness checking before the program executes. Its hybrid object orientation means that it defines non-object primitive types such as int and float, and functions can exist outside of objects.
The Ruby programming language is designed to let you write code quickly and concisely. Unlike C++, it is a very dynamic, interpreted language that includes a powerful set of libraries. While it is often referred to as a scripting language, it is a pure objected-oriented language that has sufficient expressiveness for general-purpose applications.
In Ruby, variables do not need to be declared and are free to change type from statement to statement. So the following code, where the variable x changes from a FixNum (an integer that fits within a native machine word) to a String to an Array, is a perfectly legal sequence of Ruby code:
x = 10
x += 4
x = "My String"
x = [1, "My String", Hash.new ]
A significant downside of Ruby's dynamism is its use of an interpreter. Ruby's runtime performance just can't compare to a compiled language like C++. So even if you find yourself in love with the features of Ruby, you're likely better off sticking with C++ if you really need runtime efficiency.
Having digested some of the key differences between C++ and Ruby, you're now ready to examine the small, complete example application implemented with each language. The application calculates the total number of occurrences for each word found in a set of files with a given directory, and generates an XML file that summarizes these occurrences as output. Listing 1 shows the C++ implementation, and Listing 2 shows the Ruby implementation. (Download the listings here.)