Math is an important part of programming. Ruby supports the following arithmetic operators:
x = 5
y = 2
# outputs 7
# outputs 3
# outputs 10
# outputs 2
The modulus operator, represented by the percentage symbol (%), represents the remainder of a division operation.
x = 9
y = 5
# outputs 4
The ** represents the exponent operator for raising a number to a power to perform exponentiation.
a = 2
b = 5
# this raises 2 to the power of 5 and outputs 32
The result is 32, as 2*2*2*2*2 = 32.
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 += y # x=x+y
x -= y # x=x-y
x *= y # x=x*y
x /= y # x=x/y
x %= y # x=x%y
x **= y # x=x**y
Ruby also supports parallel assignment of variables. This enables multiple variables to be initialized with a single line of code.
x = 10
y = 20
z = 30
may be more quickly initialized using parallel assignment:
x, y, z = 10, 20, 30
CLICK ON THE BUTTON BELOW TO GO TO THE RUBY MAIN COURSE PAGE.
© License: All Rights Reserved
CONTACT HOLLA TECH – LEARN SUPPORT