LanguagesShould Ruby Be Added to Your Programming Repertoire?

Should Ruby Be Added to Your Programming Repertoire?

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

As a longtime aficionado of scripting languages such as PHP, Perl, and Python, I’m kicking myself for only recently learning more about Ruby, an open source, purely object-oriented scripting language. Created by Yukihiro Matsumoto over a decade ago, the language has long been popular in Japan. But, lack of English documentation slowed U.S. adoption until just a few years ago when a few programmers discovered this rare jewel and began touting the language’s capabilities. Yet, it was only very recently that Ruby really started capturing the attention of the larger programming community, most notably due to the considerable excitement raised by the fascinating Ruby on Rails (affectionately known as simply Rails) Web framework.

Indeed, Rails is quite impressive, inasmuch that it will be the focus of a future article in this short series on Ruby; however, it’s important to understand the language’s capabilities far supercede its present supposition as a giant killer in the Web technology arena. In this inaugural article, I’ll introduce you to Ruby’s finer features, hopefully painting a picture that will sway you towards wanting to learn more about one of the more promising scripting languages to come about in a long time.

Why Another Language?

Good question. Many programmers seem to loathe the idea of learning another language, instead choosing to use their anointed language as a hammer, smashing any screw/nail/thumbtack/poptart to be thrown their way. Or worse, paraphrasing a great quote I heard at the recent PyCon conference, when all a programmer has is a hammer, all screws appear to be stupid. That said, learning another language will not only enhance your knowledge of other languages in your repertoire, but it could very well open up new routes for landing contracts and jobs otherwise falling outside of your typical sandbox. Regardless of this, I think pondering the question of why other languages should be borne is akin to debating the merits of travelling to another planet. Or creating an alternative Web framework. Or sampling another flavor of ice cream. In short, perhaps the better question to ponder is why not? Of course, one would hope that each new language adopts the positive features of its predecessors while shunning the negative. It’s with this mindset that Ruby was created.

On creating Ruby, Matsumoto recounts his intent to follow the rule of least surprise, logically meaning he wanted to ensure the language behaved in a manner causing the least amount of confusion, or surprise. The result was a language that is 100% object-oriented, dynamically typed, devoid of superfluous syntactical requirements such as indentation and semi-colons, and replete with libraries for facilitating practically any conceivable task. Ruby offers numerous signficant features; among those are the following:

  • All of the capabilities expected of full-featured languages, including text file processing, string manipulation, networking, exception handling, and language extendability.
  • Support for a wide variety of platforms, including many UNIX flavors, Windows 95/98/NT/Me/2000/XP, and Mac OS X.
  • Web application development opportunities through mod_ruby, an Apache module for embedding the Ruby interpreter into the Apache Web server.
  • A database-independent interface similar to Perl’s DBI module. Presently, there are drivers (DBDs) available for DB2, InterBase, mSQL, MySQL, Oracle, PostgreSQL, SQLite, and others.
  • The ability to create cross-platform GUI-based applications via projects like wxRuby.
  • Easy package and application management using RubyGems. RubyGems operates similarly to the inestimably useful Perl CPAN, enabling complete control over packages through a convenient console interface.
  • Built-in support for Web Services through packages such as RSS and soap.
  • A hyper-active user community. Just check out the Ruby Application Archive and RubyForge for a sampling of the hundreds of projects presently under development.

Given such features, it’s easy to understand why Ruby has is capturing the attention of so many programmers. Read on to learn how you can install and begin using the language.

Installing Ruby

In this section, I’ll offer a brief overview of the installation process for both the UNIX and Windows platforms.

Installing Ruby on Unix

You can download the latest Ruby source from here: http://www.ruby-lang.org/en/20020102.html.

Once downloaded, Ruby installs just like any other typical distribution:

%>./configure [options]
%>make
%>make test
%>make install

As always, you’ll need to possess superuser privileges to install Ruby in its standard location (/usr/local). If you’d like to change the installation directory or any other default option, execute the following to learn more about the configuration options:

%>./configure --help

Note: If you’re running Mac OS X, you may be surprised to know that Ruby is installed by default on versions 10.2 and greater.

That’s it! Once installation completes, move on to the “Using the Interactive Shell” section.

Installing Ruby on Windows

If you’re running Windows, the easiest way to install Ruby is to go to the following Web site and download the installer: http://RubyInstaller.RubyForge.org/.

Once downloaded, just double-click on the installer to begin the installation process. Review the ReadMe and licensing agreement, and pending acceptance of the latter, choose which components you’d like to install. Next, choose the installation folder and click Install. Once the installer completes, move on to the next section.

Using the Interactive Shell

Ruby comes with the Interactive Ruby (irb) shell that allows you to execute Ruby commands on-the-fly. Open up a terminal and execute irb. You’ll receive the following prompt:

irb(main):001:0>

From here, you can start experimenting with the language. To give you a feel for the language syntax, consider a real-world scenario. Suppose you want to determine the length of an e-mail address. Begin by assigning the address to a variable:

irb(main):001:0> email = "jason@example.com"
=> "jason@example.com"

Next, determine the length of the email variable. Because Ruby treats everything as an object, you can call upon the length method, which will return the total number of characters:

irb(main):003:0> length = email.length
=> 17

In line with Ruby’s intent to make programming as easy as possible, we can consolidate these two statements, producing the length like so:

irb(main):004:0> "jason@example.com".length
=> 17

If you wanted to output length in conjunction with perhaps a user-friendly string indicating the number’s context, you’ll need to enclose the variable or method in special syntax, like so:

irb(main):005:0> puts "Email address length: #{email.length}"
=> Email address length: 17

The #{} syntax is used to tell the interpreter that the delimited string should be evaluated rather than output verbatim.

What about retrieving the e-mail’s domain name? The split method should take care of this quite nicely. In fact, you can use it to retrieve both the domain and username:

irb(main):006:0> components = email.split(/@/)
=> ["jason", "example.com"]
irb(main):007:0> puts "The username is #{components[0]}"
The username is jason
=> nil
irb(main):008:0> puts "The domain is #{components[1]}"
The domain is example.com
=> nil

As you can see, split returns an array consisting of substrings divided according to the delimiter, in this case @.

Of course, while the irb is great for experimentation, most of your time will be spent writing scripts and then executing them with the Ruby interpreter. This is the topic of the next section.

Script Execution

Executing a Ruby script is as easy as placing a few commands in a text file and executing the file with the ruby interpreter:

%>ruby [program file]

For example, place the following commands in a file, saving it as datefun.rb:

# What's your birthday?

bday = DateTime.new(1975, 07, 04)

# What's today's date?

today = DateTime.now

# Difference in days between today and your birthday

daysold = today - bday

# Output difference

puts "You are #{daysold.to_i} days old."

# Were you born on a leap year?

puts "Were you born on a leap year? #{Date.leap?(bday.year)}."

# Next birthday falls on what day?

presentbday = Time.local(today.year, bday.month, bday.day)

puts "This year's birthday falls on a #{presentbday.strftime('%A')}."

Let’s execute this program and review the output:

C:rubytests>ruby datefun.rb
You are 10862 days old.
Were you born on a leap year? false.
This year's birthday falls on a Monday.

You can forego running scripts through the Ruby interpreter by adding the #! (pronounced shabang! Say it loud!) to the very first line of the script, followed by the path to your Ruby executable. For example:

#!/usr/bin/ruby

Next, make your program executable by executing:

%>chmod +x datefun.rb

Now, you should be able to execute the datefun.rb script as you would a typical program:

%>datefun.rb

I hope this brief tutorial gives you a taste of what Ruby is capable of adding to your repertoire! Stay tuned for future installments on this fascinating language.

Learning More

The Ruby language home page: http://www.ruby-lang.org/en/

Ruby Central, Inc. (non-profit organization dedicated to supporting the Ruby language): http://www.rubycentral.org/

Ruby Weekly News (a weekly summary of the ruby-talk mailing list discussions): http://rubyweeklynews.org/

The RubyGems package manager: http://rubyforge.org/projects/rubygems/

The RubyForge open source project repository: http://www.rubyforge.org/

The Ruby on Rails Web framework: http://www.rubyonrails.com/

About the Author

W. Jason Gilmore (http://www.wjgilmore.com/) spends his days (and many nights) running Apress‘ open source program. He’s the author of the best-selling Beginning PHP 5 and MySQL: Novice to Professional (Apress, 2004. 748pp.). His writings on open source technologies have been featured within many of the computing industry’s leading publications, including Linux Magazine, O’Reillynet, Devshed, Zend.com, and Webreview. Jason loves receiving e-mail, so don’t hesitate to write him at wjATwjgilmore.com.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories