5.2. Basic Operations on Numbers

The normal operations of addition, subtraction, multiplication, and division are implemented in Ruby much as in the typical programming language with the operators +, -, *, and /. Most of the operators are actually methods (and therefore can be overridden).

Exponentiation (raising to a power) is done with the ** operator as in older languages such as BASIC and FORTRAN. It obeys the “normal” mathematical laws of exponentiation.

a = 64**2    # 4096
b = 64**0.5  # 8.0
c = 64**0    # 1
d = 64**-1   # 0.015625

Division of one integer by another results in a truncated integer. This is a feature, not a bug. If you need a floating point number, make sure that at least one operand is a floating point.

3 / 3 # 3 5 / 3 # 1 3 / 4 ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.