devxlogo

Ruby—A Diamond of a Programming Language?

Ruby—A Diamond of a Programming Language?

ave you heard about Ruby? It seems to be a popular topic in software development circles today. This language came to my attention at a Java conference last spring, where gentlemen like Bruce Tate (author of Bitter Java and Better, Faster, Lighter Java), Dave Thomas (Pragmatic Programmer: From Journeyman to Master), and others were all talking about Ruby and telling many of us in the audience it deserved a look.

Now, if you are like me,you’ve been developing software for some time and you know that while learning a new programming language can be fun, you’ve been through enough of them that you probably look a little skeptically at another programming language. After all, the programming language wars in the ’80s and ’90s culminated in the conclusion that there are essentially two camps: the Java world and the development languages that Microsoft supported on .NET. Its not that I didn’t want to learn another language, I just expected that the days of switching programming languages to gain a technological advantage were over. However, given the stature of these gentlemen in the industry, I decided to take a look.

Well, “I’ve been to the mountain top” so to speak and this article is a report on what I’ve found regarding Ruby. Bottom line up front, Ruby has some very nice features and is worth your investigation.

Setting Up Ruby
Ruby is an open source programming language developed by Yukihiro “Matz” Matsumoto in Japan in the mid-90s (for more on the history of Ruby, check out this article by its founder. Ruby can be obtained at www.ruby-lang.org. Originally built as a scripting language, it is available for many platforms, including Linux, many flavors of UNIX, MS-DOS, Windows, BeOS, Amiga, Acorn Risc OS, and MacOS X. As of this writing, the latest version of Ruby is 1.8.4. For those using Windows platforms, click here for the “one-click” Windows installer. Along with the base Ruby binaries and libraries, this download comes with several helpful (and free) IDEs and tools, including: documentation and sample code, RubyGems Package Manager, FreeRIDE (Free Ruby IDE), Fox GUI Libraries, fxri (a search engine and GUI guide to Ruby’s documentation, along with an interactive command line tool), and SciTE (Scintilla Text Editor IDE). As of this writing, the “stable” version of Ruby offered through the Windows installer is 1.8.2, with a 1.8.4 version in preview form. This article was written using the 1.8.2 version of the Windows installer.

The installation of Ruby using the Windows installer is straightforward. You download and run a simple install executable (ruby182-15.exe for version 1.8.2) that initiates a standard install wizard. The download file is about 15MB and will take up almost 40MB when the wizard completes the install of Ruby on your Windows platform.

For those dedicated to using their favorite editors to program, a number of familiar editors offer Ruby support to include emacs, vim, JEdit, Jed, Nedit, and Textpad. Of course, there is also a Ruby Eclipse project. Ruby Development Tools (RDT) is an Eclipse plug-in that is still early in development but available here. Also emerging on the market are a number of inexpensive Ruby IDEs. Arachno Ruby is one such example.

Running Ruby
Like many interpreted languages, Ruby offers programmers a couple of ways to develop code. You can run Ruby in interactive mode using a command line tool or you can create a Ruby program file and ask Ruby’s interpreter to execute the program.

In Windows, bring up a Command Prompt window, simply type “ruby” at the prompt, and hit the Enter key (the Ruby in directory should be on your path for this to work). Ruby is now awaiting your program. Type in the program below, hit Control-D and then the Enter key. You should see Ruby execute your program as shown in Figure 1.

def convertCtoF (celsius)	print(celsius.to_s + " degrees celsius is " + ((celsius * 9)/5 + 32).to_s + " degrees in fahrenheit
")endconvertCtoF(20)

Figure 1. Running the Celsius to Fahrenheit Calculator in Ruby Interactively: Start Ruby and enter a program and then hit the end of file character (Control-D). Ruby displays the results and exits.
 
Figure 2. Running convertCtoF.rb: The Ruby interpreter can also execute a Ruby program file.

By the same token, the Celsius to Fahrenheit program above can be written with a Ruby IDE or simple text editor saved to a file?for example convertCtoF.rb (.rb is the conventional file type for Ruby programs). Now the Ruby interpreter will execute the Ruby program in the program file as shown in Figure 2.

The idea of having an interactive environment is not new, but it is quite powerful. Those familiar with Smalltalk, Common Lisp Object System (CLOS), or other interpreted programming environments of the past will find it very familiar. The interactive nature allows you to experiment with small chunks of programming code. A special Ruby batch file, irb.bat, kicks off the interactive Ruby interpreter and makes this point even more apparent. Figure 3 shows Ruby started using the irb.bat command. Now, code can be entered, interpreted, and tested one line at a time.


Figure 3. Interactive Ruby: In this example, the Ruby interpreter is started in interactive mode (using the irb.bat file provided with the Windows Installer) and several lines of Ruby code are entered and tested.
 
Figure 4. . fxri’s interactive Ruby Capability: The graphical language documentation guide, fxri, is also used here to run the same Ruby commands as in Figure 3, but from inside this documentation tool.

The interactive Ruby feature is built into several tools as well. For example, the graphical interface to the Ruby documentation, called fxri, not only serves as a language guide, but as an interactive Ruby interpreter as well (see Figure 4).

Objects, Methods, and Classes
In Ruby, everything is an object, and I do mean everything. Again, for those that have programmed in highly object-oriented languages such as Smalltalk, Eiffel, or CLOS, this will be a welcome surprise. In fact, one blog writer suggested that it is “time to learn Ruby or relearn Smalltalk” giving you a precursor to the nature and feel of Ruby. Numbers like 1, 2, 3 or 10.8 are all objects?not primitive types as they are in Java or C++. Strings are objects. Classes and methods are objects. For example, the following is legal Ruby code (comment lines in Ruby are demarcated with “#”):

#absolute value of the object -34-34.abs#Round a float object10.8.round#return an uppercased, reversed copy of a string object "This is Ruby".upcase.reverse#return the number of arguments to the Math "sin" method.Math.method(:sin).arity
Figure 5. Ruby Is All Objects: In Ruby, integers, floats, strings, and even classes and methods are all objects. The code here demonstrates method calls on these types of objects.

And in Ruby, work is done by calling on methods or operations of objects. What may look like a function or a procedure call in other programming languages is, in fact, a method call in Ruby.

As in all object-oriented programming languages, objects are created from classes. Many pre-built classes are provided with the Ruby library. You can modify these classes or build your own classes. Classes are defined with the “class” keyword. Class names start with an uppercase letter. Class definitions end with the “end” keyword. So a Rectangle class can be defined with the following code.

class Rectangleend

To add methods to the class, use the keyword def. Methods also end with the end keyword. Method parameters follow the def keyword and method name. Adding an area method to the Rectangle class above would look like the following code.

class Rectangle	def area (hgt, wdth)		return hgt*wdth	endend

For those familiar with other programming languages, you may have noticed a few differences. Ruby does not use any braces to delimit classes or methods, nor does it use semi-colons or other characters to denote the end of programming lines. The goal of Ruby, according to its creator, is to be simple, easy and “fun” to code. Who wants to remember all those semi-colons? Not fun. As long as you put statements on one line, no semi-colons or other code line ending mark is needed. By the way, the parentheses around the arguments to the area method are not required either. And by default, Ruby returns the last thing evaluated in a method, so the return keyword is not required. Therefore, you could have simply coded Rectangle as shown below:

class Rectangle	def area hgt, wdth		hgt*wdth	endend

While legal, it is recommended that parentheses be used for method parameters for better legibility.

Instance Variables and Attributes
Classes can also have instance variables (also known as properties in some languages). For example, objects created from the Rectangle class should all have a height and width. In Ruby, instance variables do not explicitly have to be declared in the class, they simply have to be used and annotated with a special character in their name. Specifically, all instance variable names begin with an “@.” To store the height and width in the instance of rectangle when the area method is invoked, you merely have to add instance variables to the area method:

class Rectangle	def area (hgt, wdth)		@height=hgt		@width = wdth		@height*@width	endend

More appropriately, when an instance of Rectangle gets created, the height and width should be specified and the instance variables set at that time. Ruby provides a special method called initialize to allow you to set up or prepare new instances of the class:

class Rectangle	def initialize (hgt, wdth)		@height = hgt		@width = wdth	end	def area ()		@height*@width	endend

To create a new object or instance of Rectangle, you call on the standard Ruby constructor method “new” against the class?in this case, Rectangle:

Rectangle.new(4,7)

Or, if you prefer the same instantiation without parentheses, although again for clarity’s sake, I would recommend using parentheses:

Rectangle.new 4,7

In this example, a new Rectangle object will get created, and the initialize method is called with the parameters of 4 and Rectangle class also defined methods for granting access. Notice, in the code below, the height and width methods have been added in order to share height and width information:

class Rectangle	def initialize (hgt, wdth)		@height = hgt		@width = wdth	end	def height		return @height	end	def width		return @width	end	def area ()		@height*@width	endend

Likewise, in order for some other object to update or set the height and width of a Rectangle object, additional mutating methods need to be defined:

class Rectangle	def initialize (hgt, wdth)		@height = hgt		@width = wdth	end	def height		return @height	end	def height=(newHgt)		@height=newHgt	end	def width		return @width	end	def width=(newWdth)		@width=newWdth	end	def area ()		@height*@width	endend

The mutator methods above (“height=” and “width=”) may look tricky, but they really are just methods. Don’t let the equal sign in the name fool you. The additional character at the end of the method name means nothing to Ruby, but it makes it seem more readable to humans when used. What do you think the following code looks like it is doing?

	aRectangle.height=27

That’s right, a Rectangle object’s height is being assigned/changed. In fact, it is just a call to the method “height=” on the Rectangle object.

Because granting access to an object’s instance variable is quite common, Ruby comes with a set of keywords that essentially define the instance variable and the accessor/mutator methods all at once; making these instance variables “public” attributes. The keywords are attr_reader, attr_accessor. They help simplify the code considerably:

class Rectangle	attr_accessor :height, :width		def initialize (hgt, wdth)		@height = hgt		@width = wdth	end	def area ()		@height*@width	endend

In the example code above, attr_accessor gives the Rectangle both getters and setters for the height and width attributes.

Building Applications with Interactive Ruby
So now you have a little bit of knowledge to start building a Ruby application. To demonstrate the interactive nature of the Ruby interpreter and to see how applications slowly get developed in Ruby, start an Interactive Ruby Help and Console utility (the fxri utility installed with Ruby) as shown in Figure 6.

Figure 6. Start fxri: Open the Interactive Ruby tool fxri from the Windows Start menu as shown here.

In the lower right hand pane of the window is an interactive Ruby command prompt (notice the irb(main) :001:0> command prompt) that displays when the window opens. Go ahead and enter the Figure 7 at the command prompt.

Notice that as you type in your code, the interpreter is helping to format your code and as you enter your last “end” statement, Ruby returns => nil which is an indication that the Ruby interpreter has detected the end of your Rectangle class. Rectangle is now defined in this irb session.

Now try to create a few instances of your new Rectangle class. On the very next line, enter Rectangle.new(4,5) and then Rectangle.new(5,12). You should see Ruby again respond with new instances of your Rectangle:

irb(main):011:0> Rectangle.new(4,5)=> #<0x58d2ee8><0x58cfdc8>

’’

“”


’“”

<0x587c758>

“”

“”


<0x58aa688><0x58a6ef0><0x58a4a60>


“”

<0x594db10><0x5948d58>

<0x5873f68>


“”


<0x5a18b50><0x5a139a8>


<0x59a3088><0x59a3088>






devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist