Extending Ruby with Other Languages

When you decide to use an interpreted language such as Ruby, you e trading raw speed for ease of use. Its far easier to develop a program in a higher-level language, and you get a working program faster, but you sacrifice some of the speed you might get by writing the program in a lower-level language like C and C++.

Thats the simplified view. Anyone whos spent any serious amount of time working with higher-level languages knows that the truth is usually more complex. In many situations, the tradeoff doesn really matter: if the program is only going to be run once, who cares if it takes twice as long to do its job? If a program is complex enough, it might be prohibitively hard to implement in a low-level language: you might never actually get it working right without using a language like Ruby.

But even Ruby zealots must admit that there are still situations where its useful to be able to call code written in another language. Maybe you need a particular part of your program to run blazingly fast, or maybe you want to use a particular library thats implemented in C or Java. When that happens youll be grateful for Rubys extension mechanism, which lets you call C code from a regular Ruby program; and the JRuby interpreter, which runs atop the Java Virtual Machine and uses Java classes as though they were Ruby classes.

Compared to other dynamic languages, its pretty easy to write C extensions in Ruby. The interfaces you need to understand are easy to use and clearly defined in just a few header files, there are numerous examples available in the Ruby standard library itself, and there are even tools that can help you access C libraries without writing any C code at all.

So lets break out that trusty C compiler and learn how to drop down under the hood of the Ruby interpreter, because you just never know when your next program will to turn into one of those situations where a little bit of C code is the only solution to the problem.

Garrett Rooney

Категории