rubyguides

Kernel#rand

rand(n=0) -> number

rand is a Kernel method that generates random numbers. Ruby provides several ways to generate random values depending on your needs.

Syntax

rand()        # float: 0.0 <= value < 1.0
rand(n)       # integer: 0 <= value < n
rand(range)   # value within the range

Parameters

ParameterTypeDefaultDescription
nInteger0When an integer is given, returns a random integer from 0 to n-1. When 0, returns a float between 0 and 1.
rangeRangeWhen a range is given, returns a random value within that range (integers or floats).

Examples

Basic float generation

# Generate a random float between 0 and 1
rand()
# => 0.7234567890123456

rand()
# => 0.1234567890123456

Calling rand with no arguments returns a float in the range 0.0...1.0 — the lower bound is inclusive while the upper bound is exclusive. This is the same convention Ruby uses for ranges with three dots, and it means the result will never equal 1.0, no matter how many times you call it. This form is the natural starting point when you need to scale a random value yourself.

Generating random integers

# Random integer from 0 to 9
rand(10)
# => 7

rand(10)
# => 3

# Random integer from 1 to 10
rand(1..10)
# => 5

When you pass an integer like 10, rand returns an integer from 0 up to 9 — that is, 0...n with the same exclusive upper bound as the float form. To shift the range upward you can use a Range instead, as shown in the last line above, which gives you a value from 1 to 10 inclusive without any manual offset math.

Using ranges with rand

# Float range
rand(0.0...1.0)
# => 0.4567890123456789

# Integer range
rand(1..100)
# => 42

# Negative range works too
rand(-10..-1)
# => -7

Ranges give you the most readable call sites because the bounds are visible right in the argument. A float range like 0.0...1.0 produces a float result, while an integer range like 1..100 produces an integer — the method infers the type from the range endpoints. Negative ranges work the same way, making rand usable for any numeric domain without extra arithmetic.

Common Patterns

Random selection from an array

colors = ["red", "green", "blue", "yellow"]
colors[rand(colors.length)]
# => "blue"

# Or use Array#sample (recommended)
colors.sample
# => "green"

Using rand with an array length is a straightforward way to pick a random element by index. Note that the recommended Array#sample method is more concise and handles edge cases like empty arrays gracefully — sample returns nil for an empty array while the rand + indexing approach would return nil for rand(0) but raises on an explicit negative index.

Secure random numbers

For cryptographic purposes, use SecureRandom instead:

require 'securerandom'

SecureRandom.random_number(100)    # => 87
SecureRandom.hex(16)                # => "a1b2c3d4e5f6..."
SecureRandom.alphanumeric(10)      # => "Ab3xYz9kP"

SecureRandom uses the operating system’s entropy source rather than Ruby’s internal pseudo-random generator. This matters any time the output needs to be unpredictable by an attacker — tokens, session IDs, temporary passwords, and API keys all fall into that category. The API is nearly identical to rand, so switching is usually a one-line change.

Seeding for reproducibility

Set the seed for deterministic random sequences:

srand(12345)
[rand(100), rand(100), rand(100)]
# => [42, 47, 89]

srand(12345)
[rand(100), rand(100), rand(100)]
# => [42, 47, 89]  Same results!

Treat rand as a source of variation

rand is useful whenever you need a small amount of variation without bringing in a larger random library. It can give you a float for sampling, an integer for indexing, or a value from a range when the bounds matter. The method is simple enough to use directly, but the calling code should still make the purpose clear. A random choice in a game, a test fixture, or a quick preview generator all make sense because the code is asking for controlled variation rather than exact repeatability.

Choose the right form

The argument shape matters. A bare call returns a float between zero and one, which is useful when you want to scale the result yourself. An integer argument gives you a bounded integer, which is handy for array indexing or picking a random slot. A range keeps the upper and lower limits visible at the call site. That variety makes rand flexible, but it also means the surrounding code should show which version it expects so the result is not surprising.

Keep randomness separate from security

rand is fine for everyday variation, but it is not the right tool for cryptographic work. If the value affects tokens, passwords, or anything attackers should not predict, use SecureRandom instead. That distinction is important because the method name alone does not tell you how strong the randomness is. When the goal is testing, sampling, or a light-weight choice, rand is usually enough. When the goal is secrecy, reach for the stronger tool and say so in the code.

See Also