Introduction To Ruby
Arithmetic Operators

Standard arithmetic operators are defined in Ruby.

%Modulus (remainder)
**Exponentiation (raising to a power)


The dynamic typing in Ruby means that care needs to be taken to get the result you want from division. If both of the operands (the numbers you are dividing) are integers, the result of the division will be rounded down. If one or other of the operands is a float, the result will also be a float. The following example demonstrates this,

# Division

a = 7
b = 3
c = 7.0
d = 3.0

int_div = a/b
puts int_div

float_div = a/d
puts float_div

float_div2 = c/b
puts float_div2



The modulus operator returns the remainder when the first operand is divided by the second. The following example shows this,

# Modulus

a = 6
b = 4
c = 2

remainder = 6 % 4
puts remainder

remainder2 = 6 % 2
puts remainder2



The exponentiation operator is used to raise the first operand to a power indicated by the second. The following example shows this,

# Exponentiation

a = 2
b = 3
c = 2

two_squared = a**c
two_cubed = a**b
puts two_squared
puts two_cubed