Ruby Operators
An operator is a sign that does maths with values. Assignment shortcuts change a value and store the new value back in the same variable.
Add, subtract and multiply
Each line prints the answer to one sum.
puts 7 + 3
puts 7 - 3
puts 7 * 3Divide and find the remainder
The / sign divides one value by another. The % sign gives what is left over.
puts 7 / 2
puts 7 % 2Raise to a power
Two stars raise the first value to the power of the second value.
puts 2 ** 10
puts 3 ** 2Assignment shortcuts
Each shortcut changes count and stores the new value in count.
count = 10
count += 5
puts count
count -= 3
puts count
count *= 2
puts countExample
price = 12
items = 3
total = price * items
share = total / 4
left_over = total % 7
power = 2 ** 3
puts total
puts share
puts left_over
puts powerKey points
- + adds two values together.
- - takes the second value away from the first.
- * multiplies two values.
- / divides the first value by the second.
- % gives the remainder after a division.
- ** raises a value to a power.
- A shortcut like += adds to a variable and stores the answer back.
In this example, price is 12 and items is 3. The star multiplies them and total holds 36. The slash divides 36 by 4 and share holds 9. The percent sign gives the remainder of 36 divided by 7, which is 1. The last line raises 2 to the power of 3 and prints 8.
Note
Ruby has no ++ sign, so count += 1 is the way to add one.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the code 2 ** 10 print?