Project 2

Big Numbers

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?

image

Starting Interactive Ruby

This project is completed entirely within your terminal (or console) program and uses Interactive Ruby (known as IRB or irb).

technicalstuff In this book, I refer to the language Ruby with an initial capital letter (as a name) and lowercase ruby to mean the Ruby command. Likewise, I use IRB to mean the name of the program, and irb to mean the command.

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.

remember I use the term terminal to mean the terminal or console program, whether on Mac or Windows.

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.

Entering Numbers

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.

Doing Some Basic Math

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 images. 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

technicalstuff Programmers call this prioritization order of operations or precedence, a fancy term, indeed. If you find that lines of code aren’t working the way you thought they would, check the precedence of the code you’re using.

Supersizing the Math with Huge Numbers

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.

technicalstuff If you haven’t learned about exponents yet, all you need to know for this chapter is that it’s the same as taking a number and multiplying it by itself the number of times indicated by the exponent number. So 10**2 means multiply 10 by itself two times: 10 * 10. Sometimes you hear someone talking about exponents using the phrase some number raised to a certain power. In this example, 10 is raised to the second power.

Adding Memory by Storing Results in Variables

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.

remember Programmers usually use the word data to refer to any information they’re working on. I use that term in this book, too.

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.

technicalstuff In later projects, I describe other symbols and conventions for naming variables. The basic naming I explain here works for local variables. You’ll use some additional symbols for other purposes later on.

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

warning Ruby is pretty generous with respect to what you can name your variables. Almost anything goes. One of the few rules is that the name must not conflict with any of Ruby’s built-in names for its commands. See the following for a list. If you do this accidentally, you get a syntax error, which I explain in the next section.

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__

Using Variables to Repeat a Calculation

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.

tip Note that I used a little trick that is hard to see in a book, but that you should try on your computer: I didn’t actually keep typing that formula after the first time I entered it. Instead, I used a feature of IRB that allows me to recall a previous command. If you use the up and down arrow keys when in IRB, IRB will display earlier (or later, respectively) commands. You can make small edits to the command using the left and right arrow keys to move around. You simply press your Return (Enter) key to run the command again. This can save a lot of typing.

Fixing Things When Something Goes Wrong

What happens when you try to get Ruby to display a googolplex?

technicalstuff A googol is a fun term that means 10 raised to the 100th power. A googolplex is 1 followed by googol (10100) zeroes. Supposedly, American mathematician Edward Kasner’s 9-year-old nephew, Milton Sirotta, coined the term and defined it to be the digit “one, followed by writing zeroes until you get tired.”

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.

technicalstuff Syntax is like grammar in English. A programming language’s syntax is the structure, order, and spelling of commands and statements in that language.

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.

warning Over the course of this book, you’ll probably run into syntax errors the most often, because typos are the easiest bugs to make. When you see an error message, your best course of action is to carefully compare what you typed with the project’s code.

Trying Some Experiments

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:

  • Use variables to store all the ages for your family or friends. Now add them together. What is the total age of everyone?
  • Use Ruby to calculate the circumference of the Earth. The formula for circumference is 2 * PI * r. Pi is a special value used in geometry and other areas of math and science. Ruby provides this value to you automatically using a constant (a special variable whose value is locked down and can’t be changed). You can access this value in IRB by typing Math::PI. To complete this experiment, you need to look up the value of r, which is the radius of the Earth.
  • What is your age raised by the power of 10?
  • What is the total if you add the first ten counting numbers (1, 2, 3, and so on up to 10)?
  • Can Ruby store negative numbers? What about decimals? Try some math problems to confirm this.
  • Try changing the temperature calculation to convert degrees Celsius to Fahrenheit.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.165.246