Chapter 3.2 Numbers

Ruby consists of built-in classes for numbers, Fixnum and Bignum. Any integer that is between (-2)30 and 2((30) – 1) is assigned to an instance of Fixnum. Anything else outside that range is assigned to an instance of Bignum.

Ruby supports standard decimal (base-10) operations, octal (base-8), hexadecimal (base-16), and binary (base-2) numbers.

Example:

-1234567 = -12334567 #Fixnum

1234323424231 = 1234323424231 #Bignum

01411 = 777 #Octal

To create a binary number (base-2), prefix the number with 0b. To create an octal number (base-8), prefix the number with 0x. To create a standard, base-10 integer, type the number as normal or prefix it with 0d.

Ruby also supports the Float type. Float numbers hold fractional numbers. Example:

1.5 = 1.5 1.0e5 = 100000.0

Place a 0 next to the decimal point to notate floats using the scientific notation.

Numbers contain methods that can act on them. Use the size method to determine the number’s size. Or you may use the to_s method to convert a number to a string.

-4.abs = 4

6.zero? = false

Numbers also offer methods which include arithmetic operators. The following lists the operators and its functions:

+ : Addition

- : Subtraction

/ : Division

* : Multiplication

() : Order of operations

% : Modulus

Example:

3 + 3 = 6

8 / 4 = 2

- 4 * 3 = -12

  • Currently 2.93/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
  Flag Inappropriate Content 0 comments