A friend of mine got a trial account for lynda.com and offered it to me so I immediately jumped on their Ruby essentials course. Lynda.com is a pretty good investment if you have time. They offer a wide range of courses in all fields and they are really good quality. Well presented, easy to understand, lot of practical examples and the 25 bucks / month is relatively cheap.
But let’s get into Ruby and it’s numbers. I’m not going to go to all details but show you a few interesting stuff which are unique in Ruby or they were interesting for me.
Integer and Float
So we all know the difference between them.
And how we can find out what is what (if we don’t notice for the first time):
10.2345433.class => Float
The important thing in Ruby is if you say 10 / 3 the result might surprise you. You are going to get 3 as a result. This is the biggest pitfall as a beginner you can run into in Ruby. As Integer divided by Integer will return an Integer. If precision is important to you, you need to tell that to Ruby. But if we do 10.0 / 3.0 Ruby understands that precision is important and returns 3.33333333333 .
Functions to usewith numbers
12345678.6789.round => 12345678
.round will round up the numbers for you.
12345.6789.to_i => 12345
.to_i converts your floats into integers by rounding them down.
12345.6789.floor => 12345
.floor will make sure that the number is always rounded down while
12345.6789.ceil => 12346
.ceil will do exactly the opposite and round them up (to the ceiling).
Integer, Bignum, Fixnum
Ruby integers are just numbers and make perfect sense. In Ruby they are objects of class Fixnum or Bignum. The Fixnum and Bignum classes represent integers of differing sizes.
1234.class => Fixnum
12354578.class => Bignum
And there is no Integer. But we don’t need to worry about this as the only difference between Bignum and Fixnum is the way how Ruby store these numbers as it uses more memory to store Bignums and does it more efficiently with Fixnums.
Integers can be also negative numbers and we can use a few other functions with them:
-200.abs => 200
gets the absolute value.
200.next => 201
gives the next number.
If you have any questions, comments or advise, please do share it in the comment section below.