First Steps

Interactive Ruby

We begin our exploration of Ruby with the interactive Ruby shell (irb). Open up a terminal and type:

shell> irb --simple-prompt
>> 

Make sure that you can get irb working before you move on.

Ruby as a calculator

At the simplest level, you can use ruby as a calculator. Try this:

shell> irb --simple-prompt
>> 1 + 2
=> 3
>> 4 - 3
=> 1

Ruby understands all the basic arithmetic operators that you would expect:

Symbol Meaning
+ addition
- subtraction
* multiplication
/ division

To get out of irb type exit:

shell> irb --simple-prompt
>> 1 + 2
=> 3
>> exit
shell>

You should play around with these for a bit. Try this:

>> 3 * 2
=> 6
>> 4 / 2
=> 2
>> 3 - 5
=> -2
>> 3 / 2
=> 1

Notice what happens when you try to divide 3 by 2: the result is 1.

What happened? It turns out that Ruby understands two different classes of numbers:

  • Integers (whole numbers).
  • Floats (decimal numbers).

Numbers in Ruby

Integers

An integer is a whole number, like 1, 2, -5, etc. When you operate using only integers, Ruby will give you an Integer answer.

3/2 is 1.5, but that is not an integer, so Ruby gives you 1 instead.

Floats

A float is a number with decimal places, like 3.14, 1.5, 3.0, etc. When you operate with Floats Ruby gives you a Float answer. For example:

shell> irb --simple-prompt
>> 3.0 / 2.0
=> 1.5

More operators

Before we wrap up this chapter, let’s look at two more operators:

Symbol Meaning
** exponent
% remainder

Notice how the remainder operator ‘%’ behaves with decimals. In this example, 2 goes twice into 5.1 and there is 1.1 left over.

 

What order of operations does Ruby use? Does Ruby use the standard order of operations or does it do the calculations in order from left to right (when there are multiple calculations being done on one line)?

 
 

@ianderson:


> 3 + 2 * 5

=> 13
So it looks like multiplication is done before addition as one would expect.

 
 
> (3 + 2) * 5

=> 25

works as expected

 
   

Can’t wait to start learning Ruby.