Ruby/Introduction to Ruby
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
[edit | edit source]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
[edit | edit source]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.
Installing Ruby
[edit | edit source]Windows
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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!
[edit | edit source]Let's begin with a Hello world! program in Ruby:
#!/usr/bin/ruby
# This is a comment.
print "Hello world!\nPress ENTER to continue . . ."
gets
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:
#!
[edit | edit source]#!/usr/bin/ruby
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
[edit | edit source]# This is a 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 "Hello world!\nPress ENTER to continue . . ."
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, print
displays a string (the string is the text enclosed in double-quotes) immediately after it (the string itself is a parameter of print
).
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:
Input | Description |
---|---|
\a | Bell/alert (0x07) |
\b | Backspace (0x08) |
\e | Escape (0x1b) |
\f | Formfeed (0x0c) |
\n | Newline (0x0a) |
\r | Return (0x0d) |
\s | Space (0x20) |
\t | Tab (0x09) |
\v | Vertical tab |
Variables and Gets
[edit | edit source]The next and final line
gets
essentially prompts the user to input a string via the gets
command (short for get string
) 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 gets
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)
#!/usr/bin/ruby
print "What is your name?"
name=gets.chomp
print "Hello, #{name}!"
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:
Local | Global | Instance | Class | Constant |
---|---|---|---|---|
bane | $quux | @epsilon | @@complete | Python |
carpetCleaner | $_ | @point_1 | @@ruBy | PsI |
teh_foobar | $LISP | @C | @@J | Star |
perl1337 | $cloud9 | @_ | @@uber_leet | Zit |
_666 | $Cairo | @plan9 | @@Java | COMMANDER |
Math in Ruby
[edit | edit source]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), >, <, >=, <=, || (or
), && (and
), 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 Math
module which contains the higher-level Math methods and constants, such as Math::PI
and Math.sqrt(numeric_parameter)
.
Numeric Types
[edit | edit source]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:
7 / 3
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:
print "#{7 / 3}r#{7 % 3}"
which evaluates into:
2r1
Floating point numbers, on the other hand, do
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:
7.0 / 3.0
which evaluates to:
2.33333333333333
Numbers in Ruby also have two ranges, Fixnum
and Bignum
. Fixnum
is usually in the -(2^30)
to (2^30)-1
or -(2^62)
to (2^62)-1
range, while Bignum
depends on how much memory the user's computer has.
Strings and Math
[edit | edit source]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
[edit | edit source]Strings and numbers can also be converted from one another by using the .to_s, .to_i, and ,to_f
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
[edit | edit source]- 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 (
print
andgets
), 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
[edit | edit source]The following homework assignments may require you to read the Ruby Manual.
- 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.
- Write a Ruby script that calculates the factorial and exponent of a number without the ** operator.
- Write a Ruby script that takes full advantage of the higher-level aspects of the Math module.
- 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.