Number methods in Ruby

Ruby provides a variety of built-in methods you may use on numbers. The following is an incomplete list of integer and float methods.

Even:

Use .even? to check whether or not an integer is even. Returns a true or false boolean.

    15.even? #=> false
    4.even?  #=> true

Odd:

Use .odd? to check whether or not an integer is odd. Returns a true or false boolean.

    15.odd? #=> true
    4.odd?  #=> false

Ceil:

The .ceil method rounds floats up to the nearest number. Returns an integer.

    8.3.ceil #=> 9
    6.7.ceil #=> 7

Floor:

The .floor method rounds floats down to the nearest number. Returns an integer.

    8.3.floor #=> 8
    6.7.floor #=> 6

Next:

Use .next to return the next consecutive integer.

    15.next #=> 16
    2.next  #=> 3
    -4.next #=> -3

Pred:

Use .pred to return the previous consecutive integer.

    15.pred #=> 14
    2.pred  #=> 1
    (-4).pred #=> -5

To String:

Using .to_s on a number (integer, floats, etc.) returns a string of that number.

    15.to_s  #=> "15"
    3.4.to_s #=> "3.4"

Greatest Common Denominator:

The .gcd method provides the greatest common divisor (always positive) of two numbers. Returns an integer.

    15.gcd(5) #=> 5
    3.gcd(-7) #=> 1

Round:

Use .round to return a rounded integer or float.

    1.round        #=> 1
    1.round(2)     #=> 1.0
    15.round(-1)   #=> 20

Times:

Use .times to iterate the given block int times.

    5.times do |i|
      print i, " "
    end
    #=> 0 1 2 3 4

Math operations in Ruby

In Ruby you can perform all standard math operations on numbers, including: addition +, subtraction -, multiplication *, division /, find remainders %, and work with exponents **.

Addition:

Numbers can be added together using the + operator.

15 + 25 #=> 40

Subtraction:

Numbers can be subtracted from one another using the - operator.

25 - 15 #=> 10

Multiplication:

Numbers can be multiplied together using the * operator.

10 * 5 #=> 50

Division:

Numbers can be divided by one another using the / operator.

10 / 5 #=> 2

Remainders:

Remainders can be found using the modulus % operator.

10 % 3 #=> 1 # because the remainder of 10/3 is 1

Exponents:

Exponents can be calculated using the ** operator.

2 ** 3 #=> 8 # because 2 to the third power, or 2 * 2 * 2 = 8