How to Use Arithmetic Operators in Ruby: Simple Guide
In Ruby, you use
+, -, *, /, and % to perform addition, subtraction, multiplication, division, and modulus operations respectively. These operators work directly with numbers to calculate and return results.Syntax
Ruby uses simple symbols for arithmetic operations:
+for addition-for subtraction*for multiplication/for division%for modulus (remainder)
You write expressions by placing these operators between numbers or variables.
ruby
result = 5 + 3 result = 10 - 4 result = 6 * 7 result = 20 / 5 result = 10 % 3
Example
This example shows how to use each arithmetic operator and print the result.
ruby
a = 15 b = 4 puts "Addition: #{a + b}" puts "Subtraction: #{a - b}" puts "Multiplication: #{a * b}" puts "Division: #{a / b}" puts "Modulus: #{a % b}"
Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3
Modulus: 3
Common Pitfalls
One common mistake is integer division returning an integer instead of a decimal. For example, 5 / 2 returns 2, not 2.5. To get a decimal, use floating-point numbers like 5.0 / 2.
Also, avoid dividing by zero as it causes an error.
ruby
puts 5 / 2 # Outputs 2 (integer division) puts 5.0 / 2 # Outputs 2.5 (floating-point division) # Wrong: division by zero # puts 5 / 0 # Raises ZeroDivisionError # Right: check before dividing if b != 0 puts a / b else puts "Cannot divide by zero" end
Output
2
2.5
Cannot divide by zero
Quick Reference
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Addition | 3 + 2 | 5 |
| - | Subtraction | 5 - 1 | 4 |
| * | Multiplication | 4 * 3 | 12 |
| / | Division | 10 / 2 | 5 |
| % | Modulus (remainder) | 10 % 3 | 1 |
Key Takeaways
Use +, -, *, /, and % for basic arithmetic in Ruby.
Division with integers returns an integer; use floats for decimals.
Avoid dividing by zero to prevent errors.
Arithmetic operators work directly with numbers and variables.
Use string interpolation to display results clearly.