Ruby Programming Language
Operators and Simple Math
By Mark Ciotola
First published on January 30, 2019
Operators perform much of the processing involved in computer programs. Ruby has several operators that can perform operations on variables.
Arithmetic Operators
- = or equal sign sets the variable on the left of the symbol to the expression on its right.
- + or plus sign adds numbers, or combines text, on the left and right of the sign.
- * or multiplication sign multiplies numbers on the left and right of the sign.
- ** or exponentiation sign raises the numbers on the left to the power on the right of the sign.
- / or division sign divided the number on the left by the number on the right of the sign.
Comparison Operators
Comparison operators provide only two result values: True or False.
- == determines if the value on the left is the same as the value on the right of the sign. If they are the same, the the result is TRUE. If they are NOT the same, the the result is FALSE.
- != determines if the value on the left is NOT the same as the value on the right of the sign. If they are NOT the same, the the result is TRUE.
- <determines if the value on the left is less than the value on the right of the sign.
- <= determines if the value on the left is less than or equal to the value on the right of the sign.
- > determines if the value on the left is greater than the value on the right of the sign.
- >= determines if the value on the left is greater than or equal to the value on the right of the sign.
Logical Operators
Logical operators are similar to comparison operators, but they ask if a combination of conditions are true or false.
- and asks if both condition on the side of the and operator are true
- or asks if either condition on the side of the or operator are true. Only one of the conditions needs to be true for the entire expression to be true. For example “( 100 < 500) or (20 < 1)” would be true, since 100 is indeed less than 500.
Example
After all that, we will use a simple example. We want to calculate income. We will assume an aggressive interest rate and assign the interest variable a value of a constant multiplied by the time variable.
[code lang=”ruby”]
# Goal: to calculate interest income.
# Identify variable and initialize parameters
# Initial sum of money which is a number
income = 0.0 # Float
# Interest rate which is a number
time = 0 # Integer
# Calculate and Display Results while time
income = 10.0 ∗ time
[/code]
# Goal: to calculate interest income. # Identify variable and initialize parameters # Initial sum of money which is a number income = 0.0 # Float # Interest rate which is a number time = 0 # Integer # Calculate and Display Results while time income = 10.0 ∗ time