Menu
Coddy logo textTech

Arithmetic Shortcuts

Part of the Fundamentals section of Coddy's Ruby journey — lesson 13 of 88.

When you need to update a variable's value based on its current value, Ruby provides shorthand operators called compound assignment operators. These combine an arithmetic operation with assignment in a single step.

Instead of writing score = score + 10, you can use score += 10. Both do the same thing, but the shortcut is cleaner and more common in real code.

Here are the arithmetic shortcuts available in Ruby:

points = 100
points += 25   # Same as: points = points + 25 (now 125)
points -= 10   # Same as: points = points - 10 (now 115)
points *= 2    # Same as: points = points * 2 (now 230)
points /= 5    # Same as: points = points / 5 (now 46)
points %= 10   # Same as: points = points % 10 (now 6)

These shortcuts work with all the arithmetic operators you've learned, including modulo. They're especially useful when incrementing counters or accumulating totals, making your code more concise and readable.

challenge icon

Challenge

Easy

You are provided with the following variable:

balance = 200

Using only compound assignment operators (+=, -=, *=, /=, %=), perform the following operations on balance in order:

  1. Add 50 to balance
  2. Subtract 30 from balance
  3. Multiply balance by 2
  4. Divide balance by 4
  5. Get the remainder when balance is divided by 7

After each operation, display the current value of balance using puts. You should have 5 output lines total.

Cheat sheet

Ruby provides compound assignment operators that combine arithmetic operations with assignment:

points = 100
points += 25   # Same as: points = points + 25
points -= 10   # Same as: points = points - 10
points *= 2    # Same as: points = points * 2
points /= 5    # Same as: points = points / 5
points %= 10   # Same as: points = points % 10

Available compound assignment operators:

  • += for addition
  • -= for subtraction
  • *= for multiplication
  • /= for division
  • %= for modulo

Try it yourself

# Initial balance
balance = 200

# TODO: Write your code below
# Use compound assignment operators (+=, -=, *=, /=, %=) to:
# 1. Add 50 to balance, then print it
# 2. Subtract 30 from balance, then print it
# 3. Multiply balance by 2, then print it
# 4. Divide balance by 4, then print it
# 5. Get the remainder when balance is divided by 7, then print it
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals