Ruby/Introduction to Ruby

Lesson 1: Introduction to Ruby | Ruby Class Home | Lesson 2: Flow Control

You are encouraged to ask for assistance in the discussion page.

Ruby is a free object-oriented scripting language created by Yukihiro Matsumoto (a.k.a., Matz), named after the birthstone of his colleague.

Philosophy behind Ruby
The philosophy behind Ruby is to improve programming efficiency by getting programmers to focus on solving a problem as quickly as possible while having fun doing it, instead of having to spend valuable time manually adjusting and tweaking with the compiler (interpreter) settings. Ruby essentially follows the principle of least surprise, a fancy term for minimizing complexity and confusion.

Overview of Lesson One
By the end of this lesson, you should be able to do the following:
 * read, write, and and understand simple Ruby scripts.
 * use ruby and irb from the command line.
 * understand input and output in Ruby
 * understand the basic concepts of computer science Math in Ruby

Note: at this point, the rest of the lesson will go over the Windows version of Ruby.

Windows
First, download the one-click Ruby installer and double-click on it to install Ruby.

Next, run the DOS command prompt (E.g., in Windows 2000, you go to Start->Run and type "cmd"-- without the double-quotes-- and hit enter) and type the following command:

ruby -v

You should get this or something similar in response:

ruby 1.8.6 (2007-03-13 patchlevel 0) [i386-mswin32]

If you see this, congratulations-- you have successfully installed Ruby v1.8.6.

Linux
In Redhat linux (or on most UNIX platforms) following commands will show the information. ruby -v ruby 1.8.6 (2007-09-23 patchlevel 110) [x86_64-linux]

which ruby /usr/local/bin/ruby

Ubuntu
In Ubuntu Linux just run this from a terminal: sudo apt-get install ruby Now see if you have ruby installed with: which ruby If it says something like /usr/bin/ruby Congratulations, you have now ruby installed

Ruby Version Manager
Alternatively, you can install your Ruby implementations with a tool called rvm, or Ruby Version Manager.

RVM allows you to install Ruby implementations like so: rvm install 1.9.2 rvm install 1.9.1

You can switch between Rubies like so: rvm use 1.9.1

Installation instructions are here.

Arch Linux
On Arch Linux simply run this command: pacman -Sy ruby As root. Now see if you have ruby installed by running: which ruby As in ubuntu it should give you: /usr/bin/ruby

Using the Interactive Ruby shell
Irb (Interactive Ruby shell) is a Ruby command-line shell used for experimenting with Ruby code. It's one of the most important educational and experimental tools handed out in the Ruby distributions, the others being Ruby references (such as the Pixaxe) and fxri-- a graphical implementation of the Ruby documentation.

Irb can be activated simply by typing

irb

and hitting enter in command prompt, which in turn displays

irb(main):001:0> in command prompt. For a simpler prompt, you can instead type in

irb --simple-prompt

which in return only displays

>>

instead; it's ultimately up to you on which prompt style you want.

Feel free to experiment with Ruby commands on irb up to your heart's content.

When you are done, type exit and hit the enter key

Onward to Ruby scripting
Now that you've learned how to use irb, it's time to move on to the actual learning.

You may want a text editor-- preferably with syntax highlighting-- such as SciTE or Notepad++ to edit and create Ruby files.

Ruby files are saved with the .rb or .rbw' extension. The rb files are the typical Ruby scripts that are designed to be run in a command-line interface, while the rbw files are meant for graphical user interfaces.

Hello world!
Let's begin with a Hello world! program in Ruby:

Save this file as hello.rb and double-click it (on linux type ruby hello.rb in a terminal). You should see

Hello world! Press ENTER to continue. ..

and the program should terminate upon hitting enter (or ctrl+break/ctrl+c, though these hotkeys are usually used to break out of endless loops and memory-hogging programs).

Here is an explanation of each of the commands:

#!
The  tells the shell to use the ruby.exe interpreter in the /usr/bin/ruby directory, although this is usually redundant in the Windows operating systems as the Ruby interpreter is called automatically. If the operating system doesn't use the, it will simple interpret it as a comment.

Comment
This is a Ruby comment. Anything after the  and a single space, and right before a line break character, is a comment. Comments are useful for commenting the source code, since the interpreter completely ignores it.

Print
This line of code prints the message

Hello world! Press ENTER to continue. ..

This is the first line of Ruby that actually outputs a value to the user (you). Basically,  displays a string (the string is the text enclosed in double-quotes) immediately after it (the string itself is a parameter of  ).

You may have noticed that the output if actually two lines instead of a single line, and that the \n was omitted from the output. This is because the \n is actually a newline character (the invisible character that starts a new line in text areas). In addition to the newline character, there are a variety of escape characters that can be entered in double-quoted strings (though these values are different in single-quoted strings). Here are list of double-quote escape characters:

Variables and Gets
The next and final line

essentially prompts the user to input a string via the  command (short for  ) and then just throw that text away; this is why the program halts until the program receives a carriage return.

Besides holding up the program, the  command is also used to transfer values input by the keyboard into variables for use in choosing an option, changing a value, or naming an object. A perfect example would be this program (which asks for your name and prints it on the screen)

which utilizes several methods (such as gets.chomp, which removes the newline character) and the #{expression} in the second string to evaluate an expression.

Variables are an integral part of programming; they store values (strings, numbers, files, etc.) for use immediately (such as evaluation a Math problem) or for storing information.

The variables used in the previous code are local variables (variables that begin with a lowercase letter or underscore character), which are limited to its scope. Other usable variables are global variables (variables that begin with a $ character; global variables exist in every scope), class variables (variables that begin with the @@ characters; class variables are variables that exist in the entire class scope), instance variables (variables that begin with the @ character; these characters are limited to the scope of the instance or object they were created in), and constants/class names (variables that begin with an uppercase letter; constants and class names raise an error when a stored value is modified).

Here are the naming conventions of all the variables:

Math in Ruby
Besides displaying and retrieving strings, Ruby can also do basic and some higher-level Math.

The basic operators in Math are,  ,  ,  ,  ,  , and   (assignment, addition, subtraction, multiplication, division, modulus, and exponential power respectively).

You can also use comparison and Boolean operators with == (comparison operator; not to be confused with =, the assignment operator), >, <, >=, <=, ||, && , and <=> (returns -1, 0, or 1, depending on if the value on the left is less than, equal to, or greater than the value to the right).

Finally, there's a  module which contains the higher-level Math methods and constants, such as   and.

Numeric Types
There are also a few numeric data types Ruby uses; they are integers, and floating point numbers. Integers are basically numbers without fractional values, meaning Ruby automatically truncates the fractional portion of a number in an integer expression, such as:

which evaluates into: 2

Although this is quite cumbersome, you can use the modulo operator to add a remainder value in integer division expressions (since modulo returns the remainder of a division problem:

which evaluates into: 2r1

Floating point numbers, on the other hand,  include the fractional portion of an expression. Floating point numbers always display at least one digit to the right of the decimal point to distinguish it from integers:

which evaluates to: 2.33333333333333

Numbers in Ruby also have two ranges,  and. is usually in the  to   or   to   range, while   depends on how much memory the user's computer has.

Strings and Math
Strings can be affected by certain Math operators as well. The + operator concatenates the string on the right to the end of the left string, while the * operator multiplies the string on the left by x times on the right (if you try this the other way around, the Ruby interpreter raises an error). You can experiment with different math operators and see what they do in your own time.

Data Conversion
Strings and numbers can also be converted from one another by using the  operators (to_string, to_integer, and to_float, respectively).

Certain conversions will be easy, such as

"1337".to_f

while converts the string "1337" into

1337.0

a floating point number.

A note here: when converting strings into number, the data conversion methods read from the far left of the string and reads until it encounters a non-digit character and truncates the rest of the string. If the first character of the string was a non-digit character when converted into a number, the value of the string will evaluate to 0.

Review

 * After reading this lesson, you have learned how to install Ruby and open up the Windows command prompt. You have also learned how use irb to experiment with Ruby code and commands.
 * You learned that Ruby files end with the extension rb or rbw, and that Windows automatically calls upon the ruby.exe interpreter to read rb files.
 * You have learned about Ruby's standard input and output ( and  ), and that escape characters and expressions enclosed in #{} within strings evaluate into certain values.
 * You learned that a variable's type is dependent on the first character of the variable's name, and that different variables have different scopes.
 * You learned about basic and higher-level Math operators that can be used to evaluate numeric expressions.
 * You also learned the different number types and ranges, and that certain number types do better in different situations.
 * You also learned that strings can be affected in different ways from different Math operators.
 * Finally, you learned that you can turn strings, floats, and integers into each other using the to_s, to_f, and to_i methods.

Homework
The following homework assignments may require you to read the Ruby Manual.


 * 1) Write a Ruby script that asks for a user's first and last name, then returns the user's first name and last name capitalized, returns the length of both of their names separate and combined, and the ability to change their name again.
 * 2) Write a Ruby script that calculates the factorial and exponent of a number without the ** operator.
 * 3) Write a Ruby script that takes full advantage of the higher-level aspects of the Math module.
 * 4) Write a basic command-line interpreter that stores the name and age of three persons, allows the ability to switch users and edit individual values, display data, and exit the program only by typing three to five letter commands.