Getting Started With Ruby: A Tour of the Scripting Language

Ruby is the screwdriver that gets the job done with no fuss and no muss. This article will help you get started with Ruby.

In the world of programming languages, sometimes you don't need the overhead and performance of Java, C#, C++ and other power tools. Sometimes a scripting language, or Swiss army knife, will do.

Of Perl, Python and Ruby, only one was built from the ground up to combine scripting with object-oriented programming. If you don't know one of them, let's start with Ruby. (If you know Perl or Python, don't worry; that will make Ruby even easier to learn.)

In this article, we'll cover how to install and run a Ruby project, as well as the fundamentals of Ruby syntax and style. You'll leave knowing how to run programs to do simple file I/O or Web access and it will take about the length of a lunch break.

Getting Started With Ruby Right Now

You can download an open-source Ruby interpreter on ruby-lang.org. After getting the installer, let's create a program called hello.rb in a text editor. Here's the code:

print "What is your name? "

name = gets

name = name.chomp() #removes the CRLF from name

if name == "cheesy"

puts "You don't need this tutorial!"

else

puts "Hello " + name

end

The code looks a bit like BASIC and, to an extent, it might be. There are no parenthesis unless you want them, no semi-colons at the end of the line and, though curly braces can enclose a block, we generally use do/end.

A Bit About Ruby Style

We could keep going, showing syntax of Ruby semantics of Ruby when to do a for loop, for example, and how to add two numbers together. If you're like me, you'll end up writing a program that happens to be Ruby but looks very much like your programming language of choice. While we don't have time here to explore Ruby style in much depth, let me suggest one common approach to Ruby scripting.

Instead of solving the programming problem in the main routine, write an object. The main routine creates the object, passes input parameters into it, and perhaps prints something out. Once you've developed that habit, it's easy enough to put the objects in a code library and learn how to unit test that library.

For now, let's look at variables and control flow.

Variables: Strings, Integers, Floats and Arrays

Ruby is a strongly typed language, with integers, Boolean, decimal numbers and strings as basic data types. Data type is assigned implicitly; in the code below, "name" is a string, "val" a number and "inte" an integer:

A A A A name = gets

A A A A val = 5.5

A A A A inte = 5

If you type "5" when "name" is requested, then try to add "inte" and "name," you'll get a conversion error. Although "name" is a string, it's also an object, and has a ".to_i()" function that returns an integer. Putting the code together looks like this:

A A A A added = name.to_i() + inte

Ruby uses other functions as well; "to_s()" converts to string, for example, and "to_f()" to float.

Meanwhile, there are a lot of ways to create and access an array in Ruby. For now, here are three:

A A A A array1 = array.new(10) #Creates a size-ten empty array

A A A A array2 = array[1, 2, 3, 4,5] #Array of 5 elements that increment

A A A A array3 = array(0..9)#Array of 10 elements values 0 to 9

Arrays in Ruby are zero-based and automatically resize when you address memory out of bounds. To access the second element of array2, use "array[1]." Oh, and the # sign denotes a comment.

Control Structures: If, While, For

You've seen if before, but it's about time I introduce the non-value, nil, which works something like this:

A A A A array3 = Array[1,2,3,4,5]

A A A A if (array3[5].nil?)

A A A puts "array3 has no fifth element!"

A A A A else

A A A puts array3[5].to_s()

A A A A end

The comparison operators are similar to other languages: < for less than, > for greater than, <=for greater than or equal to and !=for not equal.

"For" and "while" can work much like they do in most languages:

A A A A #for loop through some fixed numbers

A A A A for i in (0..5)

A A A A A A A A A A puts i.to_s()

A A A A end

A A A A #For Through An Array

A A A A array4 = Array[1,2,3,4,5]

A A A A for i in 0..array4.size()-1 do

A A A A puts array4[i].to_s()

A A A A end

A A A A #while Loop

A A A A i=5

A A A A while i>1

A A A A puts i.to_s()

A A A A i=i-1

A A A A end

But that "for" loop through an array sure seems like a lot of work, doesn't it? Instead, here's how to do it with the built-in loop construct of an array:

A A A A array4.each do |value|

A A A puts value.to_s()

A A A A end

A A A A for value in array

A A A puts value.to_s()

A A A A end

File I/O and Regular Expressions

Let's say we have a file with a large number of phone numbers. We want to change all the 616-3XX phone numbers to 269-3XX. To do that, we'll loop through the file, read in each line, use a regular expression to change the values, print the line and redirect out to the new file. Here's the sample file, data.txt:

A A A A 616-355-3000

A A A A 616-400-3333

A A A A 616-555-1212

A A A A 616-888-1221

A A A A 616-222-0000

A A A A 616-111-1111

A A A A 616-545-1111

A A A A 616-300-2222

There are a huge number of ways to open and process a Ruby file. We could use a one-liner to read the file into an array and then loop through the array, or we could read the file into a single (big) string, or we could read a byte at a time.

This code loops through a line of the file at a time, treating it as an array:

A A A A File.open("data.txt", "r") do |file|

A A A file.each_line do |line|

A A A A A puts line

A A A end

A A A A end

To change the value of line, we'll use Ruby's "sub" function. Short for substitute, this takes a regular expression to match (set between forward slashes), then the string to replace it with:

This substitutes lines that begin with (the carrot) 616-3 with 269-3. To see if a given line contains 616-3, we'd do something like this:

A A A A if line1 =~/^616\-3/

A A A A #code

A A A A end if

Ruby Functions and Classes

A Here's a simple function to roll a six-sided die:

A A def roll

A A A A result = 1+rand(6)

A A A A return result

A A end

To make it a class, wrap that in a class OneDeeSix above and an "end"below. (Ends always end things, with no need for curly braces.)

REST and Other URL Handling

The "open-uri" module gives us a method to grab the entire contents of a URL into a string. Let's use the Thomas-Bayer website — a free, no-authentication REST API that converts a customer ID (a number from 1-50) into an XML payload.

A A A A require "open-uri"

A A A A print "What is your userid? "

A A A A STDOUT.flush

A A A A customerid = gets

A A A A customerid = customerid.chomp #Remove trailing newline

A A A A url = "http://www.thomas-bayer.com/sqlrest/CUSTOMER/"

A A A A data_from_url = URI.parse(url+ customerid.to_s()).read

A A A A puts data_from_url

Putting It All Together

Let's create a real Ruby program that uses a class to use the REST API to find your name given your customer ID. Type it in and run it:

require "open-uri"

require 'rexml/document'

include REXML

class Customer

A A attr_accessor :customerid

A A attr_accessor :firstname

A A attr_accessor :lastname

def initialize(customerid)

A A @customerid=customerid

A A url = "http://www.thomas-bayer.com/sqlrest/CUSTOMER/"

A A data_from_url = URI.parse(url+ customerid.to_s()).read

A A xmldoc = Document.new(data_from_url)

A A @firstname = XPath.first(xmldoc, "//CUSTOMER/FIRSTNAME").text

A A @lastname = XPath.first(xmldoc, "//CUSTOMER/LASTNAME").text

A A end

end

#-----------------------------------#

#A A A A A A A A A A "Main Routine"A A A A A A A A #

#-----------------------------------#

print "What is your userid? "

A A A A A A customerid = gets

customer = Customer.new(customerid.chomp)

puts "Your name is " + customer.firstname + " " + customer.lastname

Taking Ruby to the Next Level

Now that we've got a class to retrieve a name from a public URL, I suggest putting that in a module and learning to write a unit test for it. Learn what makes a "good"class, study parameters and structure, read up on inheritance and figure out how to tie classes together.

Start with the book Practical Object Oriented Design in Ruby but also consider Learn Ruby the Hard Way, which is available online, free and in HTML format. Also consider Codecademy. Start at the very beginning and you'll learning by programming Ruby for free. (I do mean very beginning, though; if you haven't created an account yet, you'll need to do "Hello, world" in JavaScript first.)

This completes our whirlwind tour of Ruby. Now the real learning can begin.

This story, "Getting Started With Ruby: A Tour of the Scripting Language" was originally published by CIO.

FREE Computerworld Insider Guide: IT Certification Study Tips
Join the discussion
Be the first to comment on this article. Our Commenting Policies