Limited Offer
60% OFF on all plans!

Numbers in Ruby

Work with integers, floats, rational and complex numbers, arithmetic operations, built-in numeric methods, and type conversions in Ruby.

Creating Numbers

Ruby supports Integer and Float as the two everyday numeric types. It also has Rational and Complex for precise and advanced math.

1. Integer and Float

Integers are whole numbers; Floats have a decimal point.

2. Rational and Complex

Ruby has built-in `Rational` for exact fractions and `Complex` for imaginary numbers.

Finding Min and Max

Ruby provides `min` and `max` on arrays, and `[].minmax` to get both at once. The `clamp` method constrains a value within a range.

1. min and max

Call `min` and `max` on an array, or use them as standalone comparisons.

2. clamp — Constrain a Value

`clamp(min, max)` keeps a number within a range.

Rounding Numbers

`round` rounds to the nearest value. You can specify decimal places or use negative digits for rounding to tens/hundreds.

1. round

`round` rounds to the nearest integer or to a given number of decimal places.

Floor and Ceiling

`floor` rounds down to the nearest integer; `ceil` rounds up. Both accept an optional precision argument.

1. floor and ceil

`floor` always rounds down; `ceil` always rounds up.

2. truncate — Round Toward Zero

`truncate` drops the decimal part — always rounds toward zero.

Random Numbers

Ruby's `rand` method generates random numbers. Use `Random` for seeded, reproducible sequences.

1. rand

`rand` with no argument gives a Float between 0.0 and 1.0. Pass an integer for a random integer.

2. Seeded Random (Reproducible)

Use `Random.new(seed)` to get a reproducible sequence of random numbers.

Powers and Roots

Ruby uses `**` for exponentiation. `Math.sqrt` and `Math::E`/`Math::PI` are provided by the `Math` module.

1. ** Operator

`base ** exponent` raises base to the power of exponent.

2. Math Module

The `Math` module provides `sqrt`, `cbrt`, `log`, `sin`, `cos`, and constants like `PI` and `E`.

Number ↔ String Conversion

Use `to_s` to convert a number to a string, and `to_i`/`to_f` or `Integer()`/`Float()` to convert strings back to numbers.

1. Number to String

`to_s` converts any number to a string. Pass a base argument for binary, hex, etc.

2. String to Number

`to_i` and `to_f` are lenient; `Integer()` and `Float()` are strict.

Validating Numbers

Ruby provides `Integer?`, `Float?` (Ruby 3.1+), `Numeric` type checks, and `is_a?` to validate number types.

1. Checking Numeric Type

Use `is_a?(Numeric)`, `is_a?(Integer)`, and `is_a?(Float)` for type validation.

2. Is a String a Valid Number?

Use `Integer()` / `Float()` inside a rescue block, or a regex, to validate numeric strings.

3. Special Float Values

Ruby Floats can be `Infinity`, `-Infinity`, and `NaN` (Not a Number).