This is an introduction to the Ruby programming language. Ruby is modern and extremely capable programming language, and it runs many leading websites. Several examples are included.
This is an introduction to the Ruby programming language. Ruby is modern and extremely capable programming language, and it runs many leading websites. Several examples are included.
Table of Contents
-
1. Getting Started with Ruby
Introduction
Ruby is a powerful, yet easy-to-use programming language. It can be used to create simple programs and simulations, as well as highly complicated web applications. In fact, many of the leading websites are programmed with Ruby.
History and Characteristics of Ruby
Computer scientist Yukihiro Matsumoto developed Ruby and first released it in 1995. Ruby draws from Perl, Smalltalk, Eiffel, Ada, and Lisp. [4] When creating Ruby, Matsumoto strived to develop ”a scripting language that was more powerful than Perl, and more object-oriented than Python.” [5] In fact, Ruby treats everything as an object. [4] Further, ”Ruby is designed to be human-oriented. It reduces the burden of programming. It tries to push jobs back to machines. You can accomplish more tasks with less work, in smaller yet readable code.” [5] The clean, plain-English code of the Ruby language makes learning its basics easy and intuitive. Beginners can start with a free, 20 minute online course at the Ruby Lang site. [4]. Since Ruby is free, open source software [4], it is easily affordable for new areas of social science that may not have a large funding base.
Conventions
There are several conventions we will use in this book.
Programming code mentioned in text will de denoted by
monospace
type. Sometimes they will also be in bold.Commands entered on the terminal command line shall be monotype after a greater than sign, such as:
> ruby -v
Blocks of programing code will be in their own shaded sections, such as the following, or in areas with line numbers.
# This is a simple Ruby program fruit = "pear" puts fruit.to_s
Output from a program shall be indicated in a shaded area”
Pear
Running Ruby
Command Line Utility
To use Ruby, the user needs access to their computer’s command line. On Mac OSX, the Terminal application can be used. Console is available for free for Windows. Most Linux applications come with a terminal utility under various names.
Obtaining Ruby
To run the simulation, the user must also have Ruby installed on their machine (for the examples in this article, preferably Ruby 1.9.2 or higher). Some computers have Ruby pre-installed. To find out if your computer has Ruby and its version, on the command line enter:
ruby −v
If you see something similar to the following, then you already have Ruby installed. If not, you will need to install Ruby. Conversely, you can use this website to run Ruby commands in your web browser, although its capabilities are limited.
ruby 1.9.2p290 (2011−07−09 revision 32553) [x86 64−darwin10.7.1]
Otherwise, you need to download it from the following source and install it: http://www.ruby-lang.org/en/
Installing Ruby
To install Ruby, you will need to go to the downloads site.
References
- 37Signals, Ruby on Rails. http://rubyonrails.org/, last viewed on 22 March 2013.
- Blanchard, Paul, Robert L. Devaney and Glen R. Hall, 2002, Differential Equations,second edition. Brooks/Cole.
- Ruby-Doc.org, Programming Ruby: The Pragmatic Programmer’s Guide. http://www.ruby-doc.org/docs/ProgrammingRuby/, last viewed on 22 March 2013.
- Ruby-Lang.org, About. http://www.ruby-lang.org/en/about/, last viewed on 22 March 2013.
- Bruce Steward, An Interview with the Creator of Ruby. Addison Wesley, Massachusetts, http://linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html, last viewed on 25 October 2012.
-
2. Ruby Hello World!
A traditional introduction to any programing language is to show how it would output the phrase Hello World!” In Ruby, a hello world program comprises merely one line:
puts ”Hello World!”
which would output to a terminal window:
Hello World!
The word “puts” tells Ruby to print whatever is contained to the right of the word to the terminal screen. Since “Hello World!” is a string (text characters), it must be incased in quotes.
-
3. Ruby Programming, Pseudocode and Comments
We will develop a simple simulation as an example. We will develop it steps, so that you can develop skills as you go along. Fortunately, it is possible to develop simple simulations in Ruby without using its advanced features.
The following is a simple but complete linear simulation to model income as a function of time. The only non-intuitive aspect is the need to convert variables into strings for purposes of display (e.g. time.to s).
Before actually writing a program, it is good to create a plan and outline for the program. A plan might identify:
- The goal for the program
- The types of information that will be processed
- User input
- Program output
- The major steps in achieving the program’s goal.
First, you should answer questions about what the program should do, and why you want it to do that. Soak yourself questions such as the following:
- What goal do you want the program to achieve?
- With what input shall the user provide?
- What output should the program produce?
You can write a plan and outline for your program right in the program file by using comments. This will help save time both when writing the actual program code as well as serving as documentation. Documentation is important for when yourself or someone else needs to review the code and remember the purpose of each part.
In Ruby, code that appears after a # represents explanatory comments that do not add any functionality. For example:
# This is a comment.
The first part of the plan should answer the above questions, and identify the type of information the program will process.
Our simulation will calculate interest income. So we will need to know the initial amount of money and the interest rate. We should start our outline with a title for the program, state the goal and include our types of information. We use indenting to group together information into sections.
# INTEREST INCOME CALCULATOR # Goal: to calculate interest income. # Data and information types # Initial sum of money which is a number # Interest rate which is a number
Then we need to plan and outline exactly what the program will do. Our program needs to establish initial values for the sum and interest rate. We will call these initial values parameters. It will also need to calculate the interest income. So we add two comment lines to our outline.
# INTEREST INCOME CALCULATOR # Goal: to calculate interest income. # Data and information types # Initial sum of money which is a number # Interest rate which is a number # Initialize Parameters # Calculate and Display Results
This outline will make writing and organizing the actual code much easier.
-
4. Ruby Variables
Data is placed in containers called variables. As their name suggests, you can change the value in these containers. Ruby has several variable types. We will use the local variable type.
The first step is to name your variables. Variable names should be short and descriptive, and avoid special characters unless specially required. Local variables should start with a lower case letter or a “_” symbol. Acceptable names can include just letters or a combination of letters and numbers, such as “income”, “_income”, “a”, “i”, “a1”, or “a2”.
Each variable has a data type. Ruby will attempt to figure out the property data type for a variable, but you can provide Ruby with hints to avoid mistakes.
Here are some of the Ruby data types:
- Integer—integer numbers, such as – 3, -2, -1, 0, 1, 2, or 3.
- Float—floating or decimal numbers such as -89.02887, 0.0, 3.14, or 98733484.2
- String—text, such as Sam, Jean, or Mary, or A, B, or C.
There are other data types, but the ones above are sufficient for our present purposes.
We can set initial values for our variables; the data type will be shown as a comment. Anything after the “#” symbol on a line is treated as a nonfunctional comment.
# INTEREST INCOME CALCULATOR # Goal: to calculate interest income. # Data and information types and initialize parameters # Initial sum of money which is a number income = 0.0 # Float # Interest rate which is a number time = 0 # Integer # Calculate and Display Results while time
Income shall be a float, since we may need to use fractional amounts of currency. We tell Ruby that income is a float variable by adding a decimal point with an extra 0 afterwards. Otherwise, Ruby will guess this is an integer variable, which would cut off anything after the decimal point. Each unit of time shall be a discrete amount. So the variable time is an integer.
-
5. Operators and Simple Math
Operators perform much of the processing involved in computer programs. Ruby has several operators that can perform operations on variables.
Arithmetic Operators
- = or equal sign sets the variable on the left of the symbol to the expression on its right.
- + or plus sign adds numbers, or combines text, on the left and right of the sign.
- * or multiplication sign multiplies numbers on the left and right of the sign.
- ** or exponentiation sign raises the numbers on the left to the power on the right of the sign.
- / or division sign divided the number on the left by the number on the right of the sign.
Comparison Operators
Comparison operators provide only two result values: True or False.
- == determines if the value on the left is the same as the value on the right of the sign. If they are the same, the the result is TRUE. If they are NOT the same, the the result is FALSE.
- != determines if the value on the left is NOT the same as the value on the right of the sign. If they are NOT the same, the the result is TRUE.
- <determines if the value on the left is less than the value on the right of the sign.
- <= determines if the value on the left is less than or equal to the value on the right of the sign.
- > determines if the value on the left is greater than the value on the right of the sign.
- >= determines if the value on the left is greater than or equal to the value on the right of the sign.
Logical Operators
Logical operators are similar to comparison operators, but they ask if a combination of conditions are true or false.
- and asks if both condition on the side of the and operator are true
- or asks if either condition on the side of the or operator are true. Only one of the conditions needs to be true for the entire expression to be true. For example “( 100 < 500) or (20 < 1)” would be true, since 100 is indeed less than 500.
Example
After all that, we will use a simple example. We want to calculate income. We will assume an aggressive interest rate and assign the interest variable a value of a constant multiplied by the time variable.
[code lang=”ruby”]
# Goal: to calculate interest income.# Identify variable and initialize parameters
# Initial sum of money which is a numberincome = 0.0 # Float
# Interest rate which is a number
time = 0 # Integer
# Calculate and Display Results while time
income = 10.0 ∗ time
[/code]# Goal: to calculate interest income. # Identify variable and initialize parameters # Initial sum of money which is a number income = 0.0 # Float # Interest rate which is a number time = 0 # Integer # Calculate and Display Results while time income = 10.0 ∗ time
-
6. Basic Output
The word “puts” is used for simple output to the terminal screen. Below is some basic Ruby formatting. The “\” is called an escape character, and it tells Ruby to process the letter or symbol after that sign in a special way. For example, “\n” tells Ruby to create a new line. “\n\n” creates a blank line and then starts and content afterwards on its own line.
[code lang=”ruby”]
puts “This is a simple simulation program”
puts “\n\n” # This creates two lines
[/code]Puts outputs a string, so that every element included in a puts expression must be a string. To convert a number variable into a string, simply as “.to_s”.
To combine items of text and variables, use the “+” symbol, which means concatenate in this context. For example:
[code lang=”ruby”]
puts ”Income is ” + income.to_s + ”.”
[/code]Produces something similar to “Income is 100.” Let’s add that line to our program.
[code lang=”ruby”]
# Goal: to calculate interest income.# Identify variable and initialize parameters
# Initial sum of money which is a numberincome = 0.0 # Float
# Interest rate which is a number
time = 0 # Integer
# Calculate and Display Results
income = 10.0 ∗ time
puts ”Income is ” + income.to_s + ”.”
[/code]
-
7. Ruby Objects
While not necessary for simple simulations, the object-oriented capabilities of Ruby can make programs more modular, allow better modeling of complicated entities, and help avoid the need to rewrite code.
In orbject-oriented programming, objects represent entities, such as animals or companies. Objects belong to classes and subclasses. Subclasses inherit the characteristics of classes they are derived from, but also add their own particular characteristics to themselves.
For example, say you created a class called animal that could include characteristics such as number of legs. Then you created a subclass called dog, what could also have characteristics such as bark pitch. A dog object would inherit the characteristic such as legs. Characteristics such as number of legs or bark pitch involve data and are called properties. An object can have one or more attached methods, which are procedures that exhibit some sort of behavior.
An object is then an instance of a particular class. For example, an object named Rover would be an instance of the dog class.
Everything in Ruby is an object, and thus contains many attributes. Each variable you create is an object. When you add a “.to_s” to the end of your variable, you are really obtaining the string attribute of that object. Here are several useful attributes:
- “.to_f” returns the float attribute of the object.
- “.to_i” returns the integer attribute of the object.
- “.to_s” returns the string attribute of the object.
- “.length” returns the length of the object.
- “.inspect” returns information about the object
Source Code
The source code for the sample object-oriented Ruby program is shown below. This program illustrates the modular nature of object-oriented programs. It first creates a Regime class that applies to many different types of governments. Then the Dynasty subclass is derived from the Regime class, but adding additional descriptive information. A regime object sampleregime is created for the First French Republic, and then a dynasty object sampledynasty is created for the Romanov dynasty. The code snippet sampledynasty.title includes sampledynasty which is the name of the object and title which is the method being called.
The following simple program partly derived from [4] demonstrates Ruby’s object-oriented nature, and illustrates several object concepts.
[code lang=”ruby”]
# Create the Regime class Regime
def initialize (name) # Capitalize name of Regime @name= name. capitalize
enddef title # Create a method to output the regime name
print @name
end
def description # Add a description to the regime name
print @name + ” is the name of a regime.”
puts end
end# Create the Dynasty class as a subclass of Regime class Dynasty < Regime
def description # Add a description to the dynasty name
print ” is the name of a regime that is also a dynasty.”
puts end
end# Create new Regime and Dynasty object . sampleregime = Regime.new(”First French Republic”) sampledynasty = Dynasty.new(”Romanov”)
# Output
puts
puts “OUTPUT FROM OBJECT DEMONSTRATION”
“−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−”
sampleregime . description
sampledynasty . title # title inherited from regime class sampledynasty . description
puts # puts by itself adds an extra line of space
[/code]Results
The output displays the title of each created object, along with an appropriate description for that type of object.
OUTPUT FROM OBJECT DEMONSTRATION
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
First french republic is the name of a regime.
Romanov is the name of a regime that is also a dynasty.Reference
[4] Ruby-Lang.org, About. http://www.ruby-lang.org/en/about/, last viewed on 22 March 2013.
-
8. Loops
Loops allow us to repeat the same steps of code as many times as we desire without having to type that code multiple times.
A danger of loops that that a poorly coded loop can last forever. So we always wish to include a condition in the loop that will cause it to stop. The condition can be for the loop to run a specific number of times, or to keep running until a specified event occurs.
In the code below, the word
while
create the condition.[code lang=”ruby”]
while period < finalperiodlimit do lineargrowth = 1.0 ∗ periodexponentialgrowth = Math.exp(period)
end
[/code]
-
9. Formatted Output
There are ways to more nicely format screen output for Ruby. Typically, we will create a statement that will tell Ruby to format output into columns of specified sized. We can also use tabs to align the columns. Below is an example of code to nicely-formatted output.
The trick to nicely-formatted output is to create a string expression with formatting information. Below, that expression is to the right of the
periodstring
variable. Here is what each part does:- %2d produces a fixed number column with a width of 2.
- \t tabs the output to the right.
- %11.3f creates a floating number column that is eleven characters wide with three digits after the decimal place.
The
puts sprintf
code then prints the variables to its right using the format expression. Note: the number of columns in the expression must match the number of variables aftersprintf
.[code lang=”ruby”]
# display variables with type conversions
per = period.to s
lin = lineargrowth . to s
exp = exponentialgrowth . to s
periodstring = (”%2d\t\t%11.3f\t\t%1.3f”)

puts sprintf periodstring , per , lin ,exp
[/code]It can be difficult to fit the full variable names after the sprintf command without going to another line. So short versions of the variable names are created, such as
[code]per[/code]
,
[code]lin[/code]
and
[code]exp[/code]
.
The above code will produce output in formatted, consistently-spaced columns.
-
10. Input and Output Files
We can use input files to either input initial values for parameters, or to import large amounts of data for processing and analysis.
We can use output files to export results into a form that can then be processed by a spreadsheet, graphing software or another program.
Common formats for output files are as raw text or Comma Separated Values (CSV) files.
-
11. Advanced Topics
Ruby is extremely popular for developing web applications. Typically a framework, such as Rails, is used to automate the production of much of the code required to produce a web application, so that the programmer only needs to focus on the unique aspects of the application. Frameworks tend to be much more complicated than stand-alone Ruby programs, but they allow a mean to turn Ruby simulations into web applications. The Rails Guides are a great way to get started with Ruby on Rails.
-
12. Reference
Primary website for the Ruby language:
https://www.ruby-lang.org/en/
-
13. Troubleshooting
Here are some tips for troubleshooting.
- Do you have any version of Ruby installed? If you enter “ruby -v” on the command line, if it returns a message that begins with the word “ruby” and then a version number, you do have ruby installed.
- Do you have a recent version of ruby installed? If you enter “ruby -v” on the command line, it should returns a message that begins with the word “ruby” and then a version number that starts with at least “2”. If it starts with anything lower, you should update your Ruby installation.
-
14. Appendices
Some Useful Code Tidbits
- “.to_s” added to the end of a variable returns its string attribute. This is quite helpful for outputting combinations of string values and numerical variables.
- “\n” produces a line feed. It puts output after it to a new line.
Some Useful Unix/Linux Commands
- pwd to determine the path of your current directory
- cd directory path and nameto change to the specified directory
- cd .. to go up one level to the parent directory
- ls to view the sub-directories and files in a directory
- ls -l to view a more information-rich list of the sub-directories and files in a directory
- ls -a to view both the hidden and non-hidden sub-directories and files in a directory. Typically anything that begins with a “.” is hidden.