Project 2
When you installed Ruby, a number of tools were placed on your computer. You’ll use many of these tools time and time again as you learn to program. In this project, I show you how you can use a combination of your terminal program and Interactive Ruby to do quick experiments that let you try new things with Ruby.
You’ll start at the very beginning and explore some of the most basic things you might ask a computer to do by exploring numbers, simple math, and storing results in the computer’s memory using variables.
You probably didn’t think Ruby could be used as a calculator for gigantic numbers, did you?
This project is completed entirely within your terminal (or console) program and uses Interactive Ruby (known as IRB or irb).
To get ready for this project, locate your terminal program (on the Mac) or the console with Ruby shortcut (on Windows). When that’s running, everything else is the same.
At the command prompt, enter the irb command and press Return (Mac) or Enter (Windows):
$ irb
or
C:/> irb
if on Windows.
You now see the irb prompt:
$ irb
2.2.2 :001 >
Depending on your version of Ruby, the prompt may appear slightly different. In mine, it shows the current version of Ruby (2.2.2) and the current number of commands I’ve typed (when you first start IRB, you start on command 001). When I show you commands in IRB in this book, my version and count may be different from yours, but that’s okay.
Now IRB is ready for your commands, but before you start, let me show you how to leave IRB. The easiest way is to type exit and press Return (Enter). Alternatively, you can press Ctrl+D. You pop right out of IRB back to your terminal’s prompt.
Go back into IRB and proceed to the next section.
When you’ve started IRB, Ruby is waiting for something to do. I’ll make this super simple.
Type the number 1 and press Return (Enter).
2.2.2 :001> 1
=> 1
2.2.2 :002 >
What did Ruby do? It showed you that it was listening by printing out number 1 again. The => prompt is Ruby’s signal that it’s displaying some kind of result. After it’s done, Ruby shows you a new prompt and waits for your next command. In future examples, I won’t show you the next prompt, but you’ll always see it on your screen!
Try entering a few more numbers, and you’ll see Ruby keeps echoing your typing. Okay, this gets boring quickly, so let’s move on.
Ruby includes a large and powerful set of built-in capabilities. You use many of these capabilities as you progress through this book. One of the most basic is the capability to do simple arithmetic.
Enter 2 + 2 at the irb prompt and press Return (Enter):
2.2.2 :010 > 2 + 2
=> 4
Wow, Ruby can do math you learned in kindergarten! Let’s look at the other arithmetic operations of multiplication, division, and subtraction:
2.2.2 :011 > 10 * 5
=> 50
2.2.2 :012 > 10 / 5
=> 2
2.2.2 :013 > 10 - 5
=> 5
Here, the symbols are a little different, but you get the results you’d expect. What if you want to try something even more complicated, like writing the math formula to convert degrees Fahrenheit to Celsius:
2.2.2 :018 > (212 - 32) * 5 / 9
=> 100
You’re converting 212 degrees Fahrenheit by first subtracting 32, and then multiplying the result by . Ruby does the math and displays the result, 100 degrees Celsius, which is correct.
Why did I include the parentheses in the formula? Try it again without them. Go ahead, I’ll wait.
Did Ruby still give you the right answer?
No, because Ruby, like some other programming languages, processes lines of code in a certain order. In the case of mathematics, as well as other operations it can do, Ruby has a sense of priorities in terms of what order it will run the code. The parentheses provide a programming hint to do the math in the order you want it to be done.
Without the parentheses, Ruby runs the formula in the order of doing multiplication and division before addition and subtraction, which is very different from what you want. It’s as if Ruby thought you said:
2.2.2 :020 > 212 - (32 * 5 / 9)
=> 195
Unlike a pocket calculator, or even the calculator on a smartphone, Ruby has amazing support for some truly gigantic numbers. Give this a try:
2.2.2 :022 > 1234567890 * 9876543210 * 12345678998765432234567890
=> 150534112319147377922666710346041538891241000
There are 45 digits in that number! You can use the exponent operator (**) to raise a number by a certain power:
2.2.2 :026 > 10**2
=> 100
Try coming up with some really big numbers of your own and do some arithmetic on them.
So far, you’ve just typed in some math formulas (or expressions) and immediately seen the results. This is fine for really short tasks, and it uses you, the human, to remember results and enter them again when needed.
But computers give you not only the power to calculate, but also the ability to store information for later retrieval.
You use variables to name a piece of memory, store information in that memory, and at some later time, retrieve the information again.
In Ruby, you typically name variables using lowercase letters, numbers, and underscores (_). Ruby expects a variable to start with a lowercase letter, and then you can use any combination of other lowercase letters, numbers, or the underscore. Ruby convention is to use “snakecase” when naming a variable. Snakecase splits up words with an underscore, kind of like using a blank space between words in an English sentence.
Here are some examples of variables:
hello_world_title
programmer1
blue_eyed_cat_name
b
a2
The last two examples, b and a2, are perfectly valid but what they’re used for is a little mysterious. I suggest you use variable names that are meaningful to you. In this book, I use some very full names when the meaning needs to be clear, and I use some short names when appropriate.
To store data in a variable in Ruby, you “assign” the data to a variable using an equal sign (=):
2.2.2 :029 > age_of_my_dog = 4
=> 4
Unlike in math class, the equal sign here doesn’t mean that the left side is equivalent to the right side (there is another symbol you’ll see later that is used for that purpose). Instead, think of that equal sign as meaning “move the data on the right into the memory named with the variable on the left.”
To get the data back out of the variable, you just use the variable name as if you typed the data in directly:
2.2.2 :030 > age_of_my_dog * 7
=> 28
You can assign the results of the calculation into a new variable:
2.2.2 :031 > dogs_age_in_people_years = age_of_my_dog * 7
=> 28
BEGIN | do | next | then |
END | else | nil | true |
alias | elsif | not | undef |
and | end | or | unless |
begin | ensure | redo | until |
break | false | rescue | when |
case | for | retry | while |
class | if | return | while |
def | in | self | __FILE__ |
defined? | module | super | __LINE__ |
I want to revisit our temperature conversion formula from the preceding section. Written with a variable f for Fahrenheit. The formula was as follows:
c = (f – 32) * 5 / 9
I’m going to assign f to be the degrees Fahrenheit I want to convert into Celsius:
2.2.2 :043 > f = 212
=> 212
2.2.2 :044 > c = (f - 32) * 5 / 9
=> 100
2.2.2 :045 > f = 100
=> 100
2.2.2 :046 > c = (f - 32) * 5 / 9
=> 37
2.2.2 :047 > f = 32
=> 32
2.2.2 :048 > c = (f - 32) * 5 / 9
=> 0
The temperatures seem correct, so I’ll assume Ruby is doing the math correctly.
What happens when you try to get Ruby to display a googolplex?
In IRB, store a googol in a variable called googol:
2.2.2 :030 > googol = 10**100
=> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Now try raising 10 by a googol:
2.2.2 :031 > 10**googol
(irb):31: warning: in a**b, b may be too big
=> Infinity
I guess there are some limits to Ruby’s math skills! Here, Ruby is showing you a warning that the command you just typed isn’t working because part of the calculation is too big. It shows the results as Infinity, which seems about right to me.
Ruby tries to be helpful when some part of your program has a typo or does something unexpected. Ruby displays a warning or error message, often with information about where it found the problem in your code.
For instance, if I accidentally made a typo when doing some simple math, Ruby would tell me that I have a syntax error.
If I make an intentional spelling mistake:
2.2.2 :036 > 3j + 3
SyntaxError: (irb):36: syntax error, unexpected tIDENTIFIER, expecting end-of-input
3j + 3
^
from /usr/bin/irb:11:in '<main>'
I didn’t mean to type the letter j after the number 3, and unlike what you may write in school when learning algebra, this syntax is not valid Ruby.
Ruby displays an error message that’s a little cryptic, but if you see syntax error and a line number or location, it gives you a place to start investigating what went wrong. In this case, Ruby helpfully displayed my incorrect line with a little arrow symbol pointing at the point it thought was wrong. Thank you, Ruby!
Let’s see if Ruby can find another problem for us:
2.2.2 :037 > x + 5
NameError: undefined local variable or method 'x' for main:Object
from (irb):37
from /usr/bin/irb:11:in '<main>'
In this case, I tried to use a variable that I haven’t stored anything in. Ruby doesn’t know what to do here, because it can’t find a variable named x (yet). You often see this error if you make a typo in the name of a variable (or method, which you’ll learn about in a future project). Check your spelling and try again.
Another common Ruby error can be seen with this code:
2.2.2 :038 > x = nil
=> nil
2.2.2 :039 > x + 5
NoMethodError: undefined method '+' for nil:NilClass
from (irb):39
from /usr/bin/irb:11:in '<main>'
I haven’t explained nil yet, but for now you can think of it as Ruby’s way of representing “nothing.” The error Ruby is showing us means that it doesn’t know how to do addition with nil, which seems reasonable. In your code, this probably would mean you expected to receive results from some other part of the program, but the code returned nothing.
One last problem you occasionally see is if you try to do something with incompatible data:
2.2.2 :040 > x = "a"
=> "a"
2.2.2 :041 > x + 5
TypeError: no implicit conversion of Fixnum into String
from (irb):41:in '+'
from (irb):41
from /usr/bin/irb:11:in '<main>'
I assigned the letter a to variable x. You learn more about strings and letters in the next project. Here, though, I tried to add the number 5 to the letter a. Clearly this is nonsense. Ruby thinks so, too, and tells me that it can’t convert the data in a way to make it work.
In this project, you’ve seen some basic Ruby and how to use IRB to test out Ruby. You got to play with how Ruby can do math and how variables can help you store and recall data. Believe it or not, these are the fundamental building blocks on which modern programming is based. I explain a lot more in the coming projects, but manipulating data (numbers and arithmetic here), and storing and retrieving results, is what computers do all the time.
Take a few moments and try a few of these additional experiments:
18.221.165.246