Holla Tech - Learn

Doing Math
 

Math is an important part of programming. Ruby supports the following arithmetic operators

x = 5
y = 2

# Addition
puts x+y
# outputs 7

# Subtraction
puts xy
# outputs 3

# Multiplication
puts x*y
# outputs 10

# Division
puts x/y
# outputs 2

 

NOTE!
When you divide two integer values, the result will be an integer, as shown in the above example. If you want to have a floating point result, one operand must be a floating point value: x = 5.0 y = 2 puts x/y # outputs 2.5

Modulus Operator
 

The modulus operator, represented by the percentage symbol (%), represents the remainder of a division operation.
For example:

x = 9
y = 5
puts x%y
# outputs 4 

 

NOTE!
9 divided by 5 is 1 with a remainder of 4.

Exponent Operator
 

The ** represents the exponent operator for raising a number to a power to perform exponentiation.
For example:

a = 2
b = 5
puts a**b
# this raises 2 to the power of 5 and outputs 32

 

The result is 32, as 2*2*2*2*2 = 32.

NOTE!
9 divided by 5 is 1 with a remainder of 4.

Shorthand Assignment Operators
 

All of the arithmetic operators have corresponding shorthand forms for assignment.
For example, a = a + 8 can be written as a += 8.
The same applies to the other operators:

x +=# x=x+y
x -=# x=x-y
x *=# x=x*y
x /=# x=x/y
x %=# x=x%y
x **=# x=x**y 

 

NOTE!
These are called self-assignment operators, as they perform an assignment and an arithmetic operation at the same time.

Parallel Assignment
 

Ruby also supports parallel assignment of variables. This enables multiple variables to be initialized with a single line of code.
For example:

x = 10
y = 20
z = 30 

 

may be more quickly initialized using parallel assignment:

x, y, z = 10, 20, 30 

 

NOTE!
Parallel assignment is also useful for swapping the values held in two variables: a, b = b, a

BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE RUBY MAIN COURSE PAGE. 

RUBY MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT