Now that we’re comfortable with Ruby and it’s tools, lets start to do some basic Ruby! The first step of any language is it’s math and how to run numbers.

To insert a number, just type the number, the following are all numbers:

1 2 3 4 5 6 7 8 9 10 11 |
> irb 1.9.3-p286 :001 > 5 => 5 1.9.3-p286 :002 > 0x1F => 31 1.9.3-p286 :003 > 5.0 => 5.0 1.9.3-p286 :004 > 5.1515 => 5.1515 1.9.3-p286 :005 > 5_000_000 => 5000000 |

Again, in IRB, if you type it, it will print the result of that line. If it’s a line with just a number by itself, it’s not a useful line, but it does show it’s representation. Notice that “0x1F” results in 31? That’s because the interpreter sees that it’s in hex notation, and converts it to an integer. And the underscores in the last statement are just ignored, for code prettiness, it’s not required.

Typing numbers is great, but you can also do normal programming stuff with adding numbers and variables:

1 2 3 4 5 6 7 8 9 |
> irb 1.9.3-p286 :001 > variable = 5 => 5 1.9.3-p286 :002 > another_variable = variable+5 => 10 1.9.3-p286 :003 > variable = 10 => 10 1.9.3-p286 :004 > another_variable = variable+5 => 15 |

So you can set variables using the equals sign just like in most languages, and use them elsewhere, and the plus sign is used for mathematical sum. Your fairly standard operations work:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
> irb 1.9.3-p286 :001 > 5+5 => 10 1.9.3-p286 :002 > 5-5 => 0 1.9.3-p286 :003 > 5*5 => 25 1.9.3-p286 :004 > 5/5 => 1 1.9.3-p286 :005 > 5/4 => 1 1.9.3-p286 :006 > 5/4.0 => 1.25 1.9.3-p286 :007 > 10%5 => 0 1.9.3-p286 :008 > 10/5 => 2 1.9.3-p286 :009 > 8%5 => 3 |

If you’re interested, there’s a whole Math library that does things like atan, sqrt, etc:

1 2 3 4 5 |
>irb 1.9.3-p286 :001 > Math.atan(5) => 1.373400766945016 1.9.3-p286 :002 > Math.sqrt(5) => 2.23606797749979 |

A few technical notes:

- Integers in the machine size (32-bit, 64-bit), are represented natively, so they have good speed. (Fixint)
- Ruby has support for really really big integers, so if you want something really large, it can do it internally, but it’s run in software so it’s slow. (Bignum)
- Floats are always in the machine’s “double” precision, and subject to those limitations.