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.
We'll cover the following...
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 % 2returns1)
However, some of these operators are also defined on other objects, like strings and arrays.
Try these out:
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.
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.