Arithmetic Operators
Part of the Fundamentals section of Coddy's Ruby journey — lesson 11 of 88.
Ruby provides arithmetic operators to perform mathematical calculations on numbers. These operators work with both integers and floats, allowing you to build expressions just like you would in regular math.
The basic arithmetic operators in Ruby are:
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
** | Exponentiation (power) |
Here's how you can use these operators:
sum = 10 + 5 # 15
difference = 10 - 3 # 7
product = 4 * 6 # 24
quotient = 20 / 4 # 5
power = 2 ** 3 # 8 (2 to the power of 3)One important detail: when dividing two integers, Ruby performs integer division and returns only the whole number part. For example, 7 / 2 returns 3, not 3.5. To get a decimal result, at least one number must be a float: 7.0 / 2 returns 3.5.
Challenge
EasyYou are provided with the following variables:
base = 5
height = 12Calculate and display the following values, each on a separate line:
- The sum of
baseandheight - The result of
heightminusbase - The product of
baseandheight - The result of
heightdivided bybase(integer division) - The value of
baseraised to the power of3
Cheat sheet
Ruby provides arithmetic operators to perform mathematical calculations:
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
** | Exponentiation (power) |
Examples:
sum = 10 + 5 # 15
difference = 10 - 3 # 7
product = 4 * 6 # 24
quotient = 20 / 4 # 5
power = 2 ** 3 # 8Integer division: When dividing two integers, Ruby returns only the whole number part. For example, 7 / 2 returns 3. To get a decimal result, at least one number must be a float: 7.0 / 2 returns 3.5.
Try it yourself
# Variables are provided
base = 5
height = 12
# TODO: Write your code below to calculate and display:
# 1. The sum of base and height
# 2. The result of height minus base
# 3. The product of base and height
# 4. The result of height divided by base (integer division)
# 5. The value of base raised to the power of 3This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False