Ruby For Programmers – Part 1: Mathematical!

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:

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:

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:

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

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.