Ruby - Faculty Web Directory

attentionclewInternet and Web Development

Feb 2, 2013 (4 years and 9 months ago)

334 views








An Introduction to
Ruby

Senior Seminar

Andy Burnett

February 20, 2008



Table of Contents

1.

INTRODUCTION

................................
................................
................................
.................

1

2.

BACKGROUND

................................
................................
................................
....................

1

3.

THE RUBY LANGUAGE

................................
................................
................................
....

2

3.1

APPLICATIONS

................................
................................
................................
.................

2

3.2

CODE
EXPLAINED
................................
................................
................................
...........

2

4
.

RUBY ON RAILS

................................
................................
................................
..................

5

4.1

ABOUT

................................
................................
................................
................................

5

4.2

APPLICATIONS

................................
................................
................................
.................

6

4.3

EXPL
A
NATIONS

................................
................................
................................
...............

6

5
.

EXAMPLE

PROJECT CODE EXPLAINED

................................
................................
....

7

6
.

CONCLUSION

................................
................................
................................
....................

10

7
.

REFERENCES

................................
................................
................................
....................

1
1





1


1.

INTRODUCTION

Object
-
oriented programming. We have all heard it
before, but what does it really mean?
“An object is an
entity that serves as a container for data and also
controls access to the data.”

(1)

In object oriented
programming, an object is the essential element that
is associated with a set of attributes and functions that
provide an interface to the functionality of an object,
also known as methods.

(1)

In any object
-
oriented programming language,
encapsulation is crucial. This term means “first that
the attributes and methods of an object are associated
specifically with that object, or bundled with it;
second, it means that the scope of those attributes and
methods
is by default the object itself. An object is
considered to be an instance or manifestation of an
object class. The class may be thought of as the
blueprint or pattern; the object itself is the thing
created from that blueprint or pattern.”

(1)

Now that you understand the basics of objects, it
is time to jump into Ruby. If you “take the pure
object
-
orientation of Smalltalk, but remove the
quirky syntax and the reliance on a workspace; add in
the convenience and power of Perl, bu
t without all
the special cases and magic conversions; and wrap it
up in a clean syntax based in part of Eiffel, and add a
few concepts from Scheme, CLU, Sather and
common Lisp. You end up with Ruby, a language
that is already more popular than Python in i
ts native
Japan.”
(2)

Ruby is known as a language that makes
programming both fast and enjoyable. It has an “easy
to use interpreter, familiar syntax, complete object
-
oriented functionality and powerful class libraries.” It
can

be applied to a broad range of fields from text
processing and CGI scripts to professional, large
-
scale programs.”

(3)

Ruby is a very flexible language
that is taking the programming world by storm. It is
an open source langua
ge, which means that it is
totally free to use, copy, modify and distribute. The
Ruby language contains a very clean syntax which
was designed from the beginning to support the
object oriented programming model. Because
everything is an object, you can gi
ve every piece of
code properties and actions. Once familiar with Ruby
the syntax can basically be read as a spoken
language, which helps increase understanding and
ease of maintenance. It has features that make it
easily adjustable to system management as

well as
processing text files. You also don’t need to begin
programs by declaring structures or variables. When
Ruby was developed, it was based on the principle of
least surprise. This is where “all features in Ruby,
including object
-
oriented features, a
re designed to
work as ordinary programmers expect them to work.”
Some of these features include:



Interpretive programming


There is no need
for compilation; you can edit and feed your
program to the interpreter.



Dynamic programming


Types of variables
a
nd expressions as well as class and method
definitions are determined at runtime.



Familiar syntax


Easy to learn and read



Iterators


A feature for loop abstraction
where a block of code can be attached to a
method call.



Exceptions


Language
-
level suppor
t for
exception handling.



Class libraries


Cover a variety of domains,
from basic data
-
types to networking and
thread programming.



Portable


Ports to many platforms,
including Unix, DOS, Windows, OS/2, etc.
without the need for modification



Garbage coll
ection


Recycles unused
objects automatically



Built
-
in security check


Ruby’s taint model
provides safety when handling un
-
trusted
data or programs.

(3)


2.

BACKGROUND

A man by the name of Yukihiro “matz”
Matsumoto created Ruby
and released it to the public
in 1995. Ruby was originally released in Japan, but is
now becoming a more widespread and accepted
language. Ruby seems to appeal to many
programmers because of its ability to allow many
different programming styles to be expr
essed. Matz
said that he created the language because he “wanted
a language that would make him more productive and
at the same time be fun to use.” He also “wanted a
scripting language that was more powerful than Perl,
and more object
-
oriented than Python
.”
(4)

Ruby
allows you the ability to develop code incrementally
and in turn it is shorter than Perl, Python and C++.
“Matsumoto designed Ruby with a minimum of
"apparatus" and excess verbiage, such as leaders and
extensive req
uirements for variable and class
declarations.”
(4)

Over the past few years Ruby has become
extremely popular. Ruby’s primary language
discussion mailing list, Ruby
-
Talk, has been
averaging over 200 messages a day.
(5)

Ruby
received a large boost of attention in 2004 when a
new programming environment called Rails was
released. It is now ranked # 7 among programming
languages worldwide by the
TIOBE

Index, which
measures the growth of programming lan
guages.
(6)



2


3.

THE RUBY LANGUAGE


3.1

APPLICATIONS

Today, Ruby is being used world
-
wide for
text processing, XML and web applications, GUI
building, in middle
-
tier servers, and general system
administration. Ruby is used in
artificial intelligence
and mac
hine
-
learning research and as a
platform

for
exploratory mathematics. As I stated before, Ruby is
an object
-
oriented language. It is unique because
everything that you manipulate in Ruby will be an
object. “This approach diff
ers from C++ or Java
where primitive types exist or some statements do not
return a value. When writing Ruby code, or object
-
oriented code in general, the idea is to create models
in your code that render the process you are trying to
go through in code.”

(7)

An example of this would be
that if you were creating a phonebook application
you would probably want to create a list of names.
“To model that in a not
-
so
-
object
-
oriented way, you
would most likely use a series of list structures of
some sort to hold the

various sorts of data with a
synchronized way to track the position of each list.”
(7)

Object
-
oriented programming makes this simple
for you so that you can model the components you
need with objects and classes. Using the pho
nebook
as an
example, you could create a CITY class with
string attributes name and phone number. “A class’s
purpose is to model
something

in your application;
classes create the “prototype” for the nouns in your
programs: objects. Class instances, or obje
cts (the
terms are interchangeable), then take that prototype
and put it into action.”
(7)

In our

example, objects
could be created for each name in the list and they
would be instances of the CITY class. This class
could hold
data and do things related to being a name
entry, such as hold a phone number and address. It
could also enforce constraints that would be enforced
on a name entry, such as only allowing numeric
values for phone numbers.


3.2

CODE EXPLAINED

In this section, I

will be explaining some of
the basic classes that Ruby contains. I will then show
some code blocks to emphasize how the classes work
and what they look like. To begin, the first thing that
needs to be done is installing Ruby. I will be
discussing how to u
se Ruby in Windows

and Ubuntu
Linux
, so if you’re curious how to install Ruby on a
another operating system

you can navigate to the
Ruby web page for help. Sometimes installing a new
environment can be a pain, but fortunately Ruby is
quite simple to instal
l on different platforms. Inside
your browser window, navigate to
www.ruby
-
lang.org

and click on download.
In Windows,

all you
have to do is download the installer, run it, and your
done.
In Linux, you need to navig
ate to your terminal
and
type “
ruby sudo

apt
-
get install
ruby

.
A
fter
everything is all installed, you need to make sure that
you have at least a basic text editor to edit Ruby
code.
In Windows, w
hen you download Ruby, it
comes packaged with the sciTE editor. This editor
will let you highlight, open, save and run your Ruby
files for you.
It also comes packaged with a console
called

fxri
.

Fxri is a graphical interface to the Ruby
documentation.
It i
s easier to use than sciTE and is
more practical for most of the code samples. As a
side
-
note, i
n my use of fxri, using the copy/paste
function crashes the program. So, any code that you
want to mess with should be typed in manually.
In
Linux, using Ruby i
s as simple as nagivating to the
terminal and typing “
irb
”.
Now that we have the
installation out of the way, open up fxri
, or your
terminal

and let’s get started with some of the basic
classes that Ruby contains. Due to the many different
types of classes

that Ruby contains, I will only be
looking at strings, numbers, date/time, arrays and
hashes.

“Ruby provides a number of built
-
in classes
which act as building blocks for all of the
components of your application. These types differ
from those in many oth
er languages in that they all
originate from the same class originally: the object
class.”
(7)

First off, we will be looking at string
types. These types are “simply sequences of bytes
that represent a sequence of characters. Strings can be
formed a number of ways, but the most common is
likely to be using a string literal. A string literal is a
co
nstant string that is created by enclosing it in single
or double quotes.”
(7)

For example (code on right,
output on left):

puts ‘Hello, Darling.’



Hello, Darling

puts ‘What
\
’s up?’



What’s up?

puts “A
\
tTab.”




A

tab.

Now

you may be curious what the backslashes are
doing in the code. “Those are escape sequences, a
backslash followed by a character to create normally
unprintable characters (i.e. in this example I used
\
t to
create a tab character, but you can also use other
s to
create things like new lines and vertical tabs).”
(7)

Typically characters such as a single quote (‘) would
be “unprintable because it is contained in a set of
single quotes and would effectively close the set of
quotes ca
using an error.”

(7)

In the above example,
both single and double quotes are used. “Single
quoted strings are quite silly and have a very limited
set of escape sequences they can use and are typically
useless unless performance

is a concern; double
quoted strings, on the other hand, offer far more
functionality in the way of interpolation.”
(7)

Double
quoted strings offer many escape sequences. They are
listed in the table below.

3



Another feature of double quoted strings is
expression interpolation. This means that you can
insert the value of pieces of Ruby code directly into
strings.

Remember that everything in Ruby is an
object, even the results of expressions. That means
that
you can do this:

“Inches/yard: #{12*3}”



Inches/yard: 36

“#{“Tora! “*3}”




Tora! Tora! Tora!

In the second example, since the string literal creates
a string object, you can act on it just like any other
object. In this case, multiplying a string by 3 si
mply
does what you would think: makes three copies of the
string.”
(7)

Now say that you want to create a string
and use it for a few different things. First choose a
name for your string and decide what you want it to
contain.

Ruby = “Ruby is the coolest language”

Here I chose the name ‘Ruby’ for my string. I then
set the string equal to “Ruby is the coolest language”.
Now that I have a string, there are many functions
that come with it. If I ever forget the value of the
string
, I can type ‘Ruby’ into the fxri console

or irb
terminal

and it will return “Ruby is the coolest
language”. If I wanted to find the length I would type

Ruby.length


28


and it would output 28 because there are 28
characters in the string. Unlike most other
programming languages, Ruby strings are mutable,
which means that you can alter them after they are
declared. For instance, if I wanted to see my ‘Ruby’
string in uppe
rcase, I would use the upcase and
upcase! methods as demonstrated below.

Ruby.upcase



RUBY IS THE COOLEST
LANGUAGE

Ruby




Ruby is the coolest language

Ruby.upcase!



RUBY IS THE COOLEST
LANGUAGE

Ruby



RUBY IS THE COOLEST LANGUAGE

“This is one of

Ruby's syntactical conventions.

"Dangerous" methods (generally those that modify
their object in place) usually have an exclamation
mark at the end of their name. Another syntactical
convention is that predicates, methods that return a
true/false value, h
ave a question mark at the end of
their name (as in some varieties of Lisp):

string.empty?




false

string.include? 'THE'



true

“This use of English punctuation to provide the
programmer with information is an example of
Matz's design philosophy: that
Ruby is a language
primarily for humans to read and write, and
secondarily for computers to interpret.”
(8)


The next building block in Ruby’s many
classes is the Numbers class. “Numbers are as
fundamental to computing as breat
h is to human life.
Even programs that have nothing to do with math
need to count the items in a data structure, display
average running times, or use numbers as a source of
randomness.”
(8)

Fortunately, Ruby makes using
number
s easy for us, so that we can concentrate on
the more difficult aspects of programming. Numbers
consists of the Fixnum and Bignum methods. “When
creating a numeric object, any integer that is between
(
-
2
30
) and (2
30
-
1) is assigned to an instance of Fixnum
and anything else outside that range is assigned to an
instance of Bignum.”

(7)


1000.class



Fixnum

10000000000.class


Bignum

When performing arithmetic, Ruby handles any
conversions that need to me made transparently, so
you don’t have to worry about if your number is a
small or large one.

small = 1000

big = small ** 5



100000000000000

big.class




Bignum

smaller = big/big



1

smaller.class



Fixnum

(8)

Unless you want to create a string, you create
integers by entering the number you wish without
using quotations. “Ruby supports standard decimal
(base
-
10) operations, but it also supports operations

on octal (base
-
8), hexadecimal (base
-
16) and binary
(base
-
2) numbers.

(7)

If you are creating a number
besides base
-
10, you need to prefix your number with
different operators. “To create a binary number
(base
-
2), prefix the n
umber with 0b; to create an octal
number (base
-
8), prefix the number with 0; to create
a hexadecimal number (base
-
16), prefix the number
with 0x.”
(7)
. With base
-
10, no prefix is needed, but
you can use 0d if you like. In addit
ion to integer
numbers, Ruby supports fractional numbers (numbers
with a decimal) as well. These are called Float types.
With Float types, each side of the decimal point must
contain a number. “If you type a number that
includes a decimal point, Ruby creat
es a Float object
instead of Fixnum or Bignum.”

(8)

Unfortunately,
floating point numbers have size limits and can be
\
a

Bell alarm

\
f

Fo
rm feed

\
???

Octal value

\
n

New line

\
x??

Hex value

\
r

Return

#{???}

Value of ???, where
??? is a ruby
expression

\
s

Space

\
e

Escape

\
t

Tab

\
c?

Control
-
?

\
v

Vertical tab

\
M
-
?

Meta
-
?

\
b

Backspace

\
M
-
\
C
-
?

Meta
-
Control
-
?

\
v

Vertical tab

4


imprecise. Ruby provides extra classes that can
represent numbers with finite/infinite decimal
expansion and
complex (
irrational
) numbers.
(8)

Just
like everything else in Ruby, numbers are objects so
they contain methods. You can do things such as get
a numbers size or convert numbers to strings, or even
get the absolute value. All of your arithmetic
operators are also considered methods.


Loo
king at these first two classes has
maybe taken some time to read through. Luckily
Ruby has a date and time class to help keep track of
everything. Ruby supports date and time interfaces
that you may be used to from other programs, but on
top of them are R
uby
-
specific expressions that make
programming easier. Inside Ruby there are two
different time implementations. “There's a set of time
libraries written in C that have been around for
decades. Like most modern programming languages,
Ruby provides a native

interface to these C libraries.
The libraries are powerful, useful, and reliable, but
they also have some significant shortcomings, so
Ruby compensates with a second time library written
in pure Ruby. The pure Ruby library isn't used for
everything becaus
e it's slower than the C interface,
and it lacks some of the features buried deep in the C
library, such as the management of Daylight Saving
Time.”
(8)



The
Time

class in Ruby contains the
interfaces to C libraries and it is
typically all you will
need for most applications. Time objects are
represented in Ruby by the “time zero” approach.
This is the UNIX idea that time officially begins at
the first second of January 1, 1970. In order to get the
local time, you can use
Time.
now.
This will produce
the output of
Sat. March 22 13:50:26 GMT 20
08

(Or
whatever the current date and time is).
This numeric
representation isn’t very practical way to display
time. If you decide you want to use something other
than the string used above,

you can call accessor
methods to split up time into a more recognizable
form. For instance, you can call t.day to get the
numeric calendar day, t.month to get the particular
calendar month, or t.year to get the year. This is
where t = time.at(0) (seconds
-
since
-
UNIX
-
epoch).
You can handle everything from the current second
to what time zone you are in. Unfortunately, as with
all other UNIX based systems, “the biggest
shortcoming of the time class is that on a 32
-
bit
system, its underlying implementation can
’t handle
dates before December 1901 or after January 2037.”
(8)

Luckily, Ruby has you covered with their Date
and DateTime classes. “The internal representation of
a
Date

or
DateTime

object is an astronomical Julian
date: a fr
actional number of
days

since a "time zero"
in 4712 BCE, over 6,000 years ago.”

(8)

So far we
have looked at the code that you use for managing
certain moments in time. “The other use of time is
duration, the relationship between two times: "start"
and "end," "before" and "after." You can measure
duration by subtracting one
DateTime

object from
another, or one
Time

object from another: you'll get
a
result measured in days or seconds”

(8)

Duration can
come in really handy during development time. You
can use things such as benchmarking and profiling to
measure the time it takes for your program to run and
which parts run

the fastest.


Just like many other high
-
level languages,
Ruby contains built in support for arrays. Arrays are
objects that contain ordered lists of other objects. “An
array in Ruby is an ordered list of elements. Each
element is a reference to some objec
t, the way a Ruby
variable is a reference to some object.”

(8)

In order to
create a new array, you need to put a “comma
-
separated list of object references between square
brackets. The object references can be predefined
variab
les, anonymous objects created on the spot, or
expressions. A single array can contain references to
objects of many different types.

a1 = []



[]

a2 = [1, 2, 3]

[1, 2, 3]

a3 =
[1, 2, 3, 'a', 'b', 'c'
, nil]


[1, 2, 3, "a", "b", "c",
nil]

n1 = 4

n2 = 6

sum_and_difference = [n1, n2, n1+n2, n1
-
n2]



[4, 6, 10,
-
2]

If your array contains only strings, you may find it
simpler to build your array by enclosing strings in the
w{} syntax.

%w{1 2 3}


["1", "2", "3"]

%w{The rat sat

on the mat}



["The", "rat", "sat", "on", "the", "mat"]

The << operator is the simplest way to add a value to
an array. Ruby dynamically resizes arrays as
elements are added and removed.

a = [1, 2, 3]


[1, 2, 3]

a << 4.0


[1, 2, 3, 4.0]

a << 'five'


[1, 2, 3, 4.0, "five"]

Also, as in many other programming languages, the
elements of an array are numbered with indexes
starting fr
om zero. An array element can be looked
up by passing its index into the array index operator
[]. The first element of an array can be accessed with
a[0], the second with a[1], and so on.”

(8)


Similar to arrays, Ruby also
contains
hashes. “A hash literal uses braces instead of square
brackets. The literal must supply two objects for
every entry: one for the key, the other for the value.”

(9)

“You can create a Hash by calling Hash.new or
by using

one of the special
syntaxes

Hash[] or {}.
With the Hash[] syntax, you pass in the initial
elements as comma
-
separated object references. With
5


the {} syntax, you pass in the initial contents as
comma
-
separated key
-
value pairs.

empty = Hash.new

# => {}

empty ={}

# => {}

number
s = { 'two' => 2, 'eight' => 8}
# => {"two"=>2,
"eight"=>8}

numbers = Ha
sh['two', 2, 'eight', 8]
# => {"two"=>2,
"eight"=>8}

Once the hash is created, you can do hash l
ookups
and element assignments using the same syntax you
would use to view and modify array elements:

numbers["two
"]
# => 2

numbers["ten
"] = 10
# => 10

numbers # => {"two"=>2,
"eight"=>8, "ten"=>10}

You can
get an array containing the keys or values of
a hash with Hash#keys or Hash#values. You can get
the entire hash as an array with Hash#to_a:

numbers.keys

# => ["two", "eight", "ten"]

numbers.valu
es
# => [2, 8, 10]

numbers.
to_a # => [["two", 2], ["eight",
8], ["ten", 10]]

Consider some simple data for a person in an address
book. For a side
-
by
-
side comparison I'll represent
identical data as an array, then as a hash:

a = ["Maury", "Momento", "123 Elm St.",

"West
Covina", "CA"]

h = { :first_name => "Maury",


:last_name => "Momento",


:address => "123 Elm St."


:city => "West Covina",


:state => "CA" }

The array version is more concise, and if you know
the numeric index, you can retrieve
any element from
it in constant time. The

only constraint is actually
knowing the index, and
understanding

what it means.
Other than inspecting the records, there's no way to
know whether the element at index 1 is a last name or
a first name. Worse, if the

array format changes to
add an apartment number between the street address
and city, all code that uses a[3] or a[4] will need to
have its index
changed. The

hash version doesn't
have these problems. The last name will always be at
:last_name
,
and it's ea
sy (for a human, anyway) to
know what :last_name means. Most of the time, hash
lookups take no longer than array lookups.”

(8)


4.

RUBY ON RAILS


4.1

ABOUT

Let’s begin the story of Rails back in 1991 when
“Berners
-
Lee is credited as
being the father of the
World Wide Web because he developed the project
as a method of writing hypertext on the internet. That
hypertext language was HTML.”

(10)

As the web
started

to become more established, everyone from
users to developers wanted more from the
amazing
new
platform. HTML couldn’t handle all the
development so the Common Gateway Interface
(CGI) was born. This interface was created in 1993
with the Perl programming language, and it allowed
users to send and
receive data from servers and client
machines.

As the web continued to develop, languages such
as PHP and Microsoft Active Server Pages (ASP)
began to replace Perl in web application
programming. These new languages allowed
developers to add dynamic code

into regular HTML
documents.
(10)

“Another language that was giving
developers the ability to embed dynamic behavior
into the Web was JavaScript. Unlike PHP and ASP,
whose code was executed on a web server, JavaScript
was run
on the client side in the user’s browser.”

(10)

JavaScript was used for form validation, banners and
scrolling effects.

As recent as 2006, PHP, ASP and Perl are still in
use, but lately the trend has been to develop websites
b
ased off of a framework. “Frameworks are semi
complete applications that provide specific
functionality for common or repetitive tasks.”
(10)

Basically, frameworks provide the base functionality
so you don’t have to re
-
write ba
sic code over and
over again. Because of the popularity of frameworks,
during 2007 frameworks have been developed for
every web development language under the sun.
Rails was developed as a framework for Ruby and it
is also completely open source. It was “d
esigned for
writing database
-
oriented real
-
world Web
applications quickly and easily.”

(4)


Rails was created by a Danish college student
named David Heinemeier Hansson. Hansson said that
he based Rails of a project management
tool he
created called Basecamp. Hansson originally wanted
to create Basecamp using PHP, but “became
frustrated with some of the shortcomings of the
language. Many PHP programmers find themselves
in the same shoes, repeating the same code in
multiple place
s while building a system, for
example.”

(10)

Instead of using PHP, Hansson found
Ruby. He developed Basecamp on his own in two
months using Ruby. “While developing Basecamp,
Hansson realized that a lot of the code he was writi
ng
could be extracted i
nto a framework that could be
us
ed as part of other future applications.”

(10)

Rails
was born and released to public in July of 2004.
Everything contained in rails is written entirely in
Ruby. Ruby on Ra
ils (ROR) is essentially a full stack
framework. This means that every layer is “built to
work together so that you don’t repeat yourself
(DRY) and you can use a single language from top to
bottom.“

(4)

ROR provides you with a

couple of
guiding principles to keep DRY:

6




Use less software and in turn you have
less code. This “speeds up development,
helps reduce bugs and makes the code
easier to understand, maintain and
enhance.”




Use “Convention over configuration.”
“Rails doesn't

use configuration files, so
it relies instead on some simple
programming conventions that let it
figure out what it needs to know by
using information already contained in
the application code and the database
that's running.” According to Hansson,
"this
means the end of XML files telling
a story that has already been told in
code. It also means no compilation
phase: Make a change, see it work.”

(4)


4.2

APPLICATIONS

Essentially, “Ruby on Rails is a web
framework that makes it
easier to develop, deploy
and maintain web applications.”

(11)

Now any web
framework can claim to do all of these things, but
what sets Ruby on Rails (ROR) apart from the rest?

The first thing that you can look at is the
archi
tecture. Today, many developers use a Model
-
View
-
Controller architecture when building
applications. “When you develop in Rails, there’s a
place for each piece of code, and all the pieces of
your application interact in a standard way. It’s as if
you start

out with the skeleton of an application
already prepared.”

(11)


You can also look at the fact that ROR
applications are written exclusively with the Ruby
language. “Ruby is concise without being
unintelligibly terse

you can e
xpress ideas naturally
and cleanly in Ruby code. This leads to programs that
are easy to write and are easy to read months later.”

(11)

Ruby also utilizes meta
-
programming. This
means that the language makes it easy to create
m
ethods that act almost like extensions to the syntax.


Overall if ROR has a secret, it’s the power
of their naming conventions.
“The vast majority of
web applications are CRUD applications: create,
read, update and delete information from a database.
In these types of applications, ROR shines. You start
with a database schema and with almost no code, but
ROR ties together many piec
es with naming
conventions and shortcuts.”
(8)

To top everything off,
ROR has already accumulated a massive following. It
has been promoted as one of the most productive web
development frameworks of all time. As of May
2006, t
he “ROR framework has been downloaded at
least 500,000 times.”

(12)

Those numbers alone are
comparative to some of the most popular open source
frameworks in any language.



4.3

EXPLINATIONS

One of the great things about ROR is th
e
amount of documentation that comes with it. There
are a plethora of different things that you can create
with ROR and plenty of code to go along with each. I
will be looking at a short ROR program. This is a
simple application to show system status.

This

example will be demonstrated on a
machine running Ubuntu 7.1. The first thing that you
should do is make sure that you have ruby
-
gems
installed. You can do this by going to your terminal
and typing
sudo apt
-
get install ruby rubygems.
After
this you need t
o get the Rails framework. You can do
this by typing
sudo gem install rails

into your
terminal. After all of this is finished we are ready to
get started.

“To create a Rails application, run the rails
command and pass in the name of your application.
Our a
pplication will be called “status”.

$ rails status


Create


Create app/controllers


Create app/helpers


Create app/models


Create app/views/layouts


Create config/environments



A Rails application needs at least two parts: a
controller and a view.
Our controller will get
information about the system, and our view will
display it. You can generate a controller and the
corresponding view with the generate script. The
following invocation defines a controller and view
that implement a single action cal
led index. This will
be the main (and only) screen of our application.

$ cd status

$ ./script/generate controller status index


exists app/controllers/


exists app/helpers/


create app/views/status


exists test/functional/


create
app/controllers/status_controller.rb


create test/functional/status_controller_test.rb


create app/helpers/status_helper.rb


create app/views/status/index.rhtml

The generated controller is in the Ruby source file
app/controllers/status_controller.rb. That file defines
a class StatusController that implements the index
action as an empty method called index. Fill out the
index method so that it exposes the objects you want
to use in the view:

class StatusController
< ApplicationController


def index


# This variable won't be accessible to the view,
since it is local

7



# to this method


time = Time.now

# These variables will be accessible in the view, since
they are


# instance variables of the StatusContr
oller.


@time = time


@ps = 'ps aux'


end

end

The generated view is in
app/views/status/index.rhtml. It starts out as a static
HTML snippet. Open up a text editor and change it to
an ERb
(ruby script)
template that uses the instance
variables set in

StatusController#index:

<h1>Processes running at <%= @time %></h1>

<pre><%= @ps %></pre>

Now our application is complete. To run it, start up
the Rails server with the following command in the
terminal:

$ ./script/server



Booting WEBrick
\
u2026


Rails app
lication started on http://0.0.0.0:3000



Ctrl
-
C to shutdown server; call with
--
help for
options

\
u2026

You can see the application by visiting
http://localhost:3000/status/

(8)


5.

EXAMPLE PROJECT CODE
EXPLAINED

Now that I

have
explored some of

Ruby
’s

code, I
will be doing a few small projects to demonstrate the
Ruby code further. The first project is a simple tax
rate calculator.
I created this program using a text
editor called gedit on my
L
inux machine. I saved the
code as taxcalc.rb in my home folder. I then went to
my terminal and typed
ruby tax
Calc
.rb.
That
command launches the program from my home
folder and brings up the fol
lowing: (
comment,
code
,
display
)

This is the terminal line where I run the program

bars@BARSlaptop:~$ ruby taxC
alc.rb

This is the first prompt that is brought up

Enter price (excluding tax): 120

The program calculates tax and displays the answer
below

The
tax on $120.0 is $21.0, so your grand total is
$141.0

The source code for the program is as follows:

#
This initializes the tax rate

taxrate = 0.175

#
This prompts for the price before tax

print "Enter price (excluding tax): "

#
This takes the price entered
and makes sure

#
That it is greater than 0 so there isn’t negative tax

s = gets

subtotal = s.to_f

if (subtotal < 0.0) then

subtotal = 0.0

end

#
This calculates the total tax

tax = subtotal * taxrate

#
This displays the answer

puts "The tax on $#{subtotal} is

$#{tax}, so your
grand total is $#{subtotal+tax}"


This next program demonstrates some of t
he
different string methods that Ruby

can use. I looked
at the length, reverse, reverse!, upcase, capitalize,
swapcase, downcase, insert, squeeze and split
methods. While this program may have no real world
use, it is a good demonstration of string methods.
I
saved the code as
string
Method
.rb

in my home
folder. I then went to my terminal and typed
ruby
string_methods
.rb.
That command launches the
program from my home folder and brings up the
following:
(
comment,
code
,
display
)

---

s
---

The path of the righteous man is beset on all sides by
the iniquities of the selfish and the tyranny of evil
men. Blessed is he who, in the name of charity and
good will, shepherds the weak through the valley of
the darkness. For he is truly his brother's keeper and
the finder of lost children. And I will stri
ke down
upon thee with great vengeance and furious anger
those who attempt to poison and destroy my brothers.
And you will know I am the Lord when I lay my
vengeance upon you. Oh, I'm Sorry! Did I break your
concentration?

---

s.length
---

533

---

s.revers
e!
---

?noitartnecnoc ruoy kaerb I diD !yrroS m'I ,hO .uoy
nopu ecnaegnev ym yal I nehw droL eht ma I wonk
lliw uoy dnA .srehtorb ym yortsed dna nosiop ot
tpmetta ohw esoht regna suoiruf dna ecnaegnev taerg
htiw eeht nopu nwod ekirts lliw I dnA .nerdlihc t
sol
fo rednif eht dna repeek s'rehtorb sih ylurt si eh roF
.ssenkrad eht fo yellav eht hguorht kaew eht
sdrehpehs ,lliw doog dna ytirahc fo eman eht ni ,ohw
eh si desselB .nem live fo ynnaryt eht dna hsifles eht
fo seitiuqini eht yb sedis lla no teseb si n
am suoethgir
eht fo htap ehT

---

s.reverse
---

The path of the righteous man is beset on all sides by
the iniquities of the selfish and the tyranny of evil
men


---

s.upcase
---

THE PATH OF THE RIGHTEOUS MAN IS BESET
ON ALL SIDES BY THE INIQUITIES OF THE
SELFISH AND THE TYRANNY OF EVIL MEN


---

s.capitalize
---

8


The path of the righteous man is beset on all sides by
the iniquities of the selfish and the tyranny of evil
men


---

s.swapcase
---

tHE PATH OF THE RIGHTEOUS MAN IS BESET
ON ALL SIDES BY THE INIQU
ITIES OF THE
SELFISH AND THE TYRANNY OF EVIL MEN


---

s.downcase
---

the path of the righteous man is beset on all sides by
the iniquities of the selfish and the tyranny of evil
men


---

s.insert(0, "Jules Winnfield
-

" )
---

Jules Winnfield
-

the path of

the righteous man is
beset on all sides by the iniquities of the selfish and
the tyranny of evil men



---

s.squeeze
---

Jules Winfield
-

the path of the righteous man is beset
on al sides by the iniquities of the selfish and the
tyrany of evil men. blese
d is he who, in the name of
charity and god wil, shepherds the weak through the
valey of the darknes. for he is truly his brother's keper
and the finder of lost children. and i wil strike down
upon the with great vengeance and furious anger
those who atemp
t to poison and destroy my brothers.
and you wil know i am the lord when i lay my
vengeance upon you. oh, i'm sory! did i break your
concentration?

---

s.split
---

beset

on

al

sides

by

the

iniquities

of

the

selfish

and

the

tyrany

of

evil

men. …

In the
output I used an ellipsis to shorten some of the
results. The source code for the program is as
follows:

# examples of a few string methods

s = "The path of the righteous man is beset on all
sides by the iniquities of the selfish and the tyranny
of evil
men. Blessed is he who, in the name of charity
and good will, shepherds the weak through the valley
of the darkness. For he is truly his brother's keeper
and the finder of lost children. And I will strike down
upon thee with great vengeance and furious ang
er
those who attempt to poison and destroy my brothers.
And you will know I am the Lord when I lay my
vengeance upon you. Oh, I'm Sorry! Did I break your
concentration?"

#displays
original

text

puts( '
---

s
---
' )

puts(s)

#displays length of
original
text

puts( '
---

s.length
---
' )

puts(s.length)

#displays
original
text in reverse and actually
changes s

puts( '
---

s.reverse!
---
' )


puts(s.reverse!)

#creates a new string object

puts( '
---

s.reverse
---
' )



s = s.reverse

puts(s)

#displays string in uppercas
e

puts( '
---

s.upcase
---
' )

s = s.upcase

puts(s)

#displays initial char in upcase, rest to lowercase

puts( '
---

s.capitalize
---
' )


s = s.capitalize

puts(s)

#displays all uppercase letters to lowercase, all
lowercase to uppercase

puts( '
---

s.swapcase
---
' )

s = s.swapcase

puts(s)

#displays string in lowercase

puts( '
---

s.downcase
---
' )

s = s.downcase

puts(s)

#inserts substring at index

puts( '
---

s.insert(0, "Jules Winnfield
-

" )
---
' )

s = s.insert(0, "Jules Winnfield
-

" )

puts(s)

#removes repeat
ing characters
-
e.g. "xx yy"

becomes "x y"

puts( '
---

s.squeeze
---
' )

s = s.squeeze

puts(s)

# create an array of substrings

puts( '
---

s.split
---
' )


s = s.split

puts(s)

The final program that I will look at is one that I took
from
www.sapphiresteel.com
. It is a program that is a
little more complex. It has a file that contains CD
objects and gives you the option to create and save
new CDs .
I saved the code as

data_save
.rb in my
home folder
.
The storage file is named cd_db.yml.
I
then went to my terminal and typed
ruby
data_save
.rb.
That command launches the program
9


from my home folder and brings up the following:
(
comment,
code
,
display
)

---


-

!ruby/object:CD


artist: Dolly Parton


name: Greatest Hits


numtracks: 20

-

!ruby/object:PopCD


artist: Status Quo


genre: rock


name: Even Greater Hits


numtracks: 25

-

!ruby/object:ClassicalCD


artist: Bjorling


composer: Verdi


conductor: Karajan


name: Aida


numtracks: 30

-

!r
uby/object:CD


artist: The Groovettes


name: Fab Grooves


numtracks: 12

Create (P)op CD (C)lassical CD, (O)ther CD
-

(S)ave
or (Q)uit?

From here you can choose if you would like to create
a new CD, save your settings or quit.

> o

Enter CD name: Greate
st Hits

Enter artist's name: James Taylor

Enter number of tracks: 14

---


-

!ruby/object:CD


artist: Dolly Parton


name: Greatest Hits


numtracks: 20

-

!ruby/object:PopCD


artist: Status Quo


genre: rock


name: Even Greater Hits


numtracks: 25

-

!ruby/object:ClassicalCD


artist: Bjorling


composer: Verdi


conductor: Karajan


name: Aida


numtracks: 30

-

!ruby/object:CD


artist: The Groovettes


name: Fab Grooves


numtracks: 12

-

!ruby/object:CD


artist: James Taylor


name: Greatest Hi
ts


numtracks: 14

Create (P)op CD (C)lassical CD, (O)ther CD
-

(S)ave
or (Q)uit?

The save function writes all the information to a file
and then displays it again. The quit function displays
all the information that is saved and quits.

The source code is

as follows:

# Ruby Sample program from
www.sapphiresteel.com

#This adds the 'yaml' extention to the program

require 'yaml'

#array for cd objects

$cd_arr = Array.new

# file name for saving/loading

$fn = 'cd_db.yml'

# ancestor generic CD class

class CD


# initialize variables parsed from array argument


# ( arr )


def initialize( arr )


@name = arr[0]


@artist = arr[1]


@numtracks = arr[2]


end


# return an array containing all instance variables



# of a CD object


def getdetails


return[@name, @artist, @numtracks]


end

end

# PopCD is a 'child' class of CD

class PopCD < CD


# call super to pass array, arr, to parent (CD) class


# This initializes three instance variables. This



# method the initializes one more: @genre


def initialize( arr )


super( arr )


@genre = arr[3]


end


# calls sup to get arra from CD class getdetails


# method. Then adds @genre to the end of the

array



# and returns the entier 4
-
item array


def getdetails


return( super << @genre )


end

end

class ClassicalCD < CD


def initialize( arr )


super( arr )


@conductor = arr[3]


@composer = arr[4]


end


def
getdetails


return( super << @conductor << @composer )


end

end

# some methods to get data from the user

def otherCD


print( "Enter CD name: " )

10



cd_name = gets().chomp()


print( "Enter artist's name: " )


a_name = gets().
chomp()


print( "Enter number of tracks: " )


num_tracks = gets().chomp().to_i


return [cd_name, a_name, num_tracks ]

end

def classicCD


cdInfo= otherCD


print( "Enter conductor's name: " )


con_name= gets().chomp()


print( "Enter composer's name: " )


comp_name = gets().chomp()


cdInfo << con_name << comp_name


return cdInfo

end

def popCD


cdInfo= otherCD


print( "Enter genre of music: " )


genre = gets().chomp()


cdInfo << genre


return cd
Info

end

# adds a CD object to the array variable, $cd_arr

def addCD( aCD )


$cd_arr << aCD

end

# saves data to disk in YAML format

# the to_yaml method converts to YAML format

def saveDB


File.open( $fn, 'w' ) {


|f|


f.write($cd
_arr.to_yaml)


}

en
d

# loads data from disk and recreates the array of

# cd objects, $cd_arr, from the data

def loadDB


input_data = File.read( $fn )


$cd_arr = YAML::load( input_data )

end

# prints the data from the array to screen in human
-

#
readable (YAML) format

def showData


puts( $cd_arr.to_yaml )

end

# Start of Program

if File.exist?( $fn ) then


loadDB


showData

else


puts( "The file #{$fn} cannot be found.")

end

# 'main' loop

ans = ''

until ans == 'q' do


puts( "Create
(P)op CD (C)lassical CD, (O)ther CD
-

(S)ave or (Q)uit?" )


print( "> " )


ans = gets[0].chr().downcase()


case ans


when 'p' then addCD( PopCD.new( popCD()
) )


when 'c' then addCD( ClassicalCD.new(
classicCD() ) )


when 'o' then addCD( CD.new( otherC
D() )
)


when 's' then saveDB


end


showData

end


6.

CONCLUSION

As I have progressed through this tutorial, I have
addressed many different aspects of Ruby. I have
looked at the history of Ruby, how it came about and
how to use some basics of the language.
Ruby has the
benefit of being a completely open source, object
-
oriented language. It lets you use whatever style of
programming that you please, and gives you the
freedom to use the code and conventions as you
please. Today, Ruby is being used world
-
wide for
text processing, XML and web applications, GUI
building, in
middle
-
tier servers, and general system
administration. Ruby has also inspired the creation of
Ruby on Rails, a full
-
stack web framework. Ruby on
Rails has simplified the process of developing
database
-
backed web applications. The beauty of it is
that all
you need
to go live with Rails is a database
and a web server. Overall, learning about Ruby has
taught me a lot about object
-
oriented programming
and I am excited to see what the future holds for the
language. “I believe people want to express
themselves w
hen they program. They don't want to
fight with the language. Programming languages
must feel natural to programmers.”
-

Yukihiro
Matsumoto



11


Works Cited


1.
Futon, Hal.

The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition.
Crawfordsville

:
Addison Wesley Professional, 2006.

2.
Hunt, Andy and Thomas, Dave.

Programming in Ruby.
Dr. Dobbs Portal: The World of Software Development.
[Online] January 1, 20
01. [Cited: March 23, 2008.] http://www.ddj.com/web
-
development/184404436.

3.
Matsumoto, Yukihiro.

Ruby in a Nutshell.
s.l.

: O'Reilly, 2001.

4.
Kay, Russel.

Ruby On Rails.
Computer World.
November 28, 2005, p. 26.

5. Ruby.
Ruby.
[Online] [Cited: 01 18, 20
08.] www.ruby.org.

6. TIOBE Software.
TIOBE Software: Tiobe Index.
[Online] 2008. [Cited: January 15, 2008.]
http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html.

7.
McAnally, Jeremy.

Mr. Neighborly's Humble Little Ruby Book.
2006.

8.
Carlson,
Lucas and Richardson, Leonard.

Ruby Cookbook.
s.l.

: O'Reilly, 2006.

9.
Fowler, Chad, Hunt, Andy and Thomas, Dave.

Programming Ruby, Second Edition.
s.l.

: The Pragmatic
Programmers, 2005.

10.
Williams, Justin.

Rails Solutions Ruby on Rails Made Easy.
New
York

: Springer
-
Verlag, 2007.

11.
Hansson, David Heinemeier and Thomas, Dave.

Agile Web Development with Rails.
s.l.

: The Pragmatic
Programmers, 2005.

12.
Hibbs, Curt and Tate, Bruce A.

Ruby on Rails: Up and Running.
s.l.

: O'Reilly, 2006.





















Appendix


1.

Who created Ruby and where was he from?

Yukihiro “matz” Matsumoto


2.

In what year was Ruby released to the public?

1995


3.

What tool was Ruby On Rails based on?

Basecamp Project Management
tool.


4.

What does DRY stand for?

Don’t repeat yourself


5.

What programming structure does Ruby follow?

Object Oriented Programming