0
0
Rubyprogramming~5 mins

Arithmetic operators in Ruby

Choose your learning style9 modes available
Introduction

Arithmetic operators help us do math with numbers in programs. They let us add, subtract, multiply, and divide easily.

Calculating the total price of items in a shopping cart.
Finding the average score of a student.
Counting how many days are left until a holiday.
Splitting a bill evenly among friends.
Syntax
Ruby
result = number1 + number2
result = number1 - number2
result = number1 * number2
result = number1 / number2
result = number1 % number2

Use + for addition, - for subtraction, * for multiplication, / for division, and % for remainder (modulus).

Division with / returns a float if any number is a float, otherwise an integer.

Examples
Adds 5 and 3, then prints 8.
Ruby
sum = 5 + 3
puts sum
Subtracts 4 from 10, then prints 6.
Ruby
difference = 10 - 4
puts difference
Multiplies 7 by 6, then prints 42.
Ruby
product = 7 * 6
puts product
Divides 20 by 4, then prints 5.
Ruby
quotient = 20 / 4
puts quotient
Finds remainder when 17 is divided by 5, then prints 2.
Ruby
remainder = 17 % 5
puts remainder
Sample Program

This program asks for two numbers, then shows the result of adding, subtracting, multiplying, dividing, and finding the remainder.

Ruby
puts "Enter first number:"
num1 = gets.chomp.to_i
puts "Enter second number:"
num2 = gets.chomp.to_i

sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
remainder = num1 % num2

puts "Sum: #{sum}"
puts "Difference: #{difference}"
puts "Product: #{product}"
puts "Quotient: #{quotient}"
puts "Remainder: #{remainder}"
OutputSuccess
Important Notes

Division by zero will cause an error, so avoid dividing by zero.

Using to_i converts input to whole numbers; for decimals use to_f.

Summary

Arithmetic operators let you do basic math in Ruby.

Use +, -, *, /, and % for addition, subtraction, multiplication, division, and remainder.

Remember to handle division carefully to avoid errors.