Ruby

Thomas demonstrates the power and flexibility of Ruby.

Ruby is a full-fledged, modern, pure, object-oriented programming language. Its syntax is terse and consistent, making Ruby both easy to read and learn, and it's flexible and expressive as well. If you're coming from a background in an API-bloated language, you will be surprised by Ruby's small but powerful core API. That Ruby is tightly integrated with the underlying operating system, and that it is ridiculously simple to extend, makes it both a powerful and versatile programming language.

Bold assertions? Let's uncover the truths behind these claims. For demonstration, I have included a simple Ruby script that purges a temp directory of files older than a given number of days. The application lets me demonstrate both basic Ruby syntax and some of the language's more important features. The entire script is included in Listing 1 [available at ftp.linuxjournal.com/pub/lj/listings/issue95/4834.tgz]. It is invoked by

./purge.rb [tmp_dir] [max_file_age_in_days]

where age determines how old a file needs to be before it is purged from the temp directory. You can add a call to this script in your crontab.

Ruby Basics

Ruby, an object-oriented language, offers encapsulation of data and methods within objects, allows inheritance from one class to another and supports polymorphism. Everything, including primitive data types like strings and integers, is represented as an object. Even constants and classes are represented as objects. This makes Ruby a pure object-oriented language. The only exception here is the control structure, a handful of expressions such as for, if, while, etc. These are not objects.

As shown in Listing 2 [available at ftp.linuxjournal.com/pub/lj/listings/issue95/4834.tgz], the delete_older method contains the top-level program logic: traverse a given directory to check for files to delete.

To those used to typed languages like Java or C++, the method parameters' missing type declarations may seem strange. But Ruby is dynamically typed. That is, a variable has no type, but the object it holds a reference to does, hence the lack of types in the declaration. Dynamic typing favors object composition over class inheritance. There is no controlling the type of objects passed as parameters in method calls, alleviating the need to worry about complex inheritance hierarchies, as we no longer depend on polymorphism to pass objects into methods. This leads to simpler, more reusable code.

Ruby's method declaration should look familiar to Python programmers. The two languages declare methods in practically the same way, including the use of optional parameters. An optional parameter can be left out when calling a method. Leaving out the parameter is the same as invoking the method with the optional parameter's default value.

Ruby's method declaration also lacks a return value. Since the language is dynamically typed, there is no need to declare a return type. Unless a return object is explicitly specified with the return statement, the last expression evaluated will be returned, as in Lisp.

A method is invoked by sending the target object a message. This is the Smalltalk way. The target.message(parameterlist) message-passing notation should be familiar to all object-oriented programmers. Sending an object a message invokes the corresponding method on the target object. All inter-object communication is handled by message passing.

Ruby operates with the notion of two kinds of methods: class methods and what is simply called methods, or instance methods. Instance methods are invoked on instantiated classes, more commonly known as objects. Class methods are called on uninstantiated classes and are like static methods in Java and C++. As a class method is called on an uninstantiated class, it may be considered a library method. It does not operate on the object's member variables.

Containers

Consider the following code the script is invoked with, which processes the command-line parameters:

path = ARGV.shift or raise "Missing path to delete"
age  = ARGV.shift or raise "Missing age in days"

ARGV is an array object containing the command-line options from the invocation of the script. Calling “shift” returns and removes array's first element. Ruby has an advanced array class. The array is dynamic; it resizes itself. It is an object, so you need not worry about memory issues and walking off its end either. Methods allowing you to process the array by index, by element and as if it were a stack, a set or a queue, are also included with the class. Arrays may be reversed and they may be sorted. For table lookups, use the Hash class.

The following line from Listing 1 shows how elegant Ruby's array is:

Dir.entries(full_name) - ['.', '..']).empty?

Dir.entries(full_name) returns an array containing all files in the directory. The array ['.', '..'] is then subtracted from the directory listing by using with the - operator. We can then see if the directory is empty by calling isEmpty? on the directory listing. If the array is empty, i.e., isEmpty? returns true, no other files are left in the directory.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

It works

Anonymous's picture

It works

This example doesn't work,

Anonymous's picture

This example doesn't work, it is missing something so has an extra )

Dir.entries(full_name) - ['.', '..']).empty?

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState