Search⌘ K
AI Features

Arithmetic Operators

Explore how Ruby's arithmetic operators function differently based on data types. Understand addition, subtraction, multiplication, division, exponentiation, and modulo with numbers, strings, and arrays to write flexible and expressive code.

Relation between operators and operands

For numbers, the + and * operators mean the mathematical operations of adding and multiplying two numbers. There are other arithmetic operators. Here’s a full list:

  • +: Addition
  • -: Subtraction
  • *:Multiplication
  • /: Division
  • **: Exponentiation
  • %: Modulo (the signed remainder of a division, for example, 5 % 2 returns 1)

However, some of these operators are also defined on other objects, like strings and arrays.

Try these out:

Ruby
puts 2 ** (-3)
puts (-2) ** 3

Operator behavior depends on data types

Recall that some of these operators mean something different for strings. Using a + on two strings simply means that they’ll concatenate into one long string. Using a * between a string and a number repeats it that many times.

We saw something similar for arrays.

Ruby
p "ruby" + "!"
p "ruby" * 3
p [1, 2] + [3, 4]
p [1, 2] * 3

Again, the + operator serves to combine two arrays into one big array, while the * operator applied to an array and a number produces a large array with the original elements repeated.