Menu
Getting Started With Ruby: A Tour of the Scripting Language

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:

name = gets

val = 5.5

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:

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:

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

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

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:

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

if (array3[5].nil?)

puts "array3 has no fifth element!"

else

puts array3[5].to_s()

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:

#for loop through some fixed numbers

for i in (0..5)

puts i.to_s()

end

#For Through An Array

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

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

puts array4[i].to_s()

end

#while Loop

i=5

while i>1

puts i.to_s()

i=i-1

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:

array4.each do |value|

puts value.to_s()

end

for value in array

puts value.to_s()

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:

616-355-3000

616-400-3333

616-555-1212

616-888-1221

616-222-0000

616-111-1111

616-545-1111

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:

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

file.each_line do |line|

puts line

end

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:

if line1 =~/^616\-3/

#code

end if

Ruby Functions and Classes

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

def roll

result = 1+rand(6)

return result

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 &mdash; a free, no-authentication REST API that converts a customer ID (a number from 1-50) into an XML payload.

require "open-uri"

print "What is your userid? "

STDOUT.flush

customerid = gets

customerid = customerid.chomp #Remove trailing newline

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

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

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

attr_accessor :customerid

attr_accessor :firstname

attr_accessor :lastname

def initialize(customerid)

@customerid=customerid

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

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

xmldoc = Document.new(data_from_url)

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

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

end

end

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

#           "Main Routine"         #

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

print "What is your userid? "

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.

Join the CIO Australia group on LinkedIn. The group is open to CIOs, IT Directors, COOs, CTOs and senior IT managers.

Join the newsletter!

Or

Sign up to gain exclusive access to email subscriptions, event invitations, competitions, giveaways, and much more.

Membership is free, and your security and privacy remain protected. View our privacy policy before signing up.

Error: Please check your email address.

Tags softwareapplication developmentDevelopment tools

More about ----Addison-WesleyAustralian Pharmaceutical IndustriesBayer AustraliaObject Oriented

Show Comments
[]