Numbers are a fantastically useful data type in Ruby, as they are in any programming language. You'll see numbers in code in order to perform:
Making mistakes while working with numbers can be a programmer's worst nightmare. Imagine you are hired to write code for a tax calculation service, but you add a decimal point in the wrong place, and all the client's numbers are off. 🙈
That's why it's worthwhile to see how numbers work in Ruby beyond just the obvious.
Ruby number types
There's more than meets the eye when it comes to numbers in Ruby! There are two different types:
Fixnums: what you might consider to be "integers." They could be -3, 5, 80, 234, etc.
Floats: numbers with a decimal point. They could be 3.2, 100.6, etc.
If you're not sure which type of number you're dealing with, you can always run the
classmethod on the number itself:
3.2.class => Float 4.class => Fixnum
Basic math in Ruby
You can run basic math operations in Ruby. To perform certain math operations, use the following symbols:
+ for addition
- for subtraction
* for multiplication
/ for division
# Addition 5 + 2 => 7 # Subtraction 100 - 7 => 93 # Multiplication 8 * 8 => 64 # Division 144 / 12 => 12
Math operations can get a little tricky depending on whether you're working with Floats or Fixnums, the two number data types we defined above!
For example, if I run the math operation 17/9, I should get something with a decimal point, right?
17 / 9 => 1
What?! In theory, I should get 1.something, but instead, I just get a whole number of 1.
This is because I ran a math operation on two Fixnums (numbers without decimal points). If I want my answer to include decimal places, I need at least one of the numbers in my math operation to include a decimal point as well:
17.0 / 9.0 => 1.8888888888888888
Working with numbers in Ruby has obvious uses. You can count the number of times a user has logged in, how much they owe on an outstanding balance, how many comments they've left (and limit them if it's too many), and more.
If you feel ready for it, take numbers for a spin in a real practical example by following the screencast below in which we go over how to show a user an error if their password is too long. This requires counting the number of characters in a password (string) and comparing that value to a maximum defined value.
There's an interactive code exercise below the screencast that will allow you to follow along, or as usual, you can follow along in irb in Terminal.