Numbers

Integers

Integers are whole numbers: counts, ages, and indexes. They can be positive, negative, or zero, and Ruby handles very large integers without extra effort.

Underscores may split long digits into groups of three. They are ignored by the interpreter and exist only for human eyes:

seats = 42 crowd = 1_000_000 puts seats # prints 42 puts crowd # prints 1000000

Floats

Floats are numbers with a decimal point: prices, weights, and averages. Any number written with a dot becomes a float, even when the fraction is zero.

price = 9.99 whole = 3.0 puts price # prints 9.99 puts whole # prints 3.0

Basic math

The usual operators work as expected: plus, minus, multiply, divide, remainder, and power. Watch out for one detail: dividing two integers drops the fraction and returns an integer.

2 + 3 # => 5 2 ** 10 # => 1024 7 / 2 # => 3 7.0 / 2 # => 3.5

When at least one side is a float, the result is a float. That is the simplest way to keep the decimal part of a division.

To_i to_f round

Input from users and files arrives as strings, so Ruby offers small converters with clear names. to_i turns a string into an integer, to_f into a float, and round trims a float to the nearest whole number.

"42".to_i # => 42 "3.5".to_f # => 3.5 3.7.round # => 4 3.2.round # => 3

Next: Strings

Article author: Arthur Isaev