Kernel#srand

srand(seed=nil) -> old_seed
Returns: Integer · Updated March 13, 2026 · Kernel Methods
random numbers seed reproducibility

The srand method seeds Ruby’s pseudo-random number generator. By setting a specific seed, you can generate the same sequence of random numbers every time, which is essential for testing and debugging.

How It Works

Ruby’s random number generator is deterministic—given the same seed, it produces the same sequence. This is useful when you need reproducible results.

Practical Examples

Basic Usage

# Seed with a specific number
srand(12345)
rand(10)   # => 7 (always with seed 12345)
rand(10)   # => 2
rand(10)   # => 4

# Reset to same seed for reproducibility
srand(12345)
rand(10)   # => 7 again!
rand(10)   # => 2 again!
rand(10)   # => 4 again!

Testing and Debugging

# In tests, you want deterministic behavior
def shuffle_deck
  srand(42)  # Always same shuffle for testing
  cards = (1..52).to_a.shuffle
  # Now test can assert specific order
end

# With RSpec
before { srand(0) }  # Deterministic rand for all tests

Multiple Random Sequences

# Each seed gives different sequence
srand(1)
sequence1 = 5.times.map { rand(100) }  # [17, 51, 64, 43, 47]

srand(2)
sequence2 = 5.times.map { rand(100) }  # [72, 57, 8, 21, 51]

srand(1)  # Back to seed 1
sequence1_again = 5.times.map { rand(100) }  # Same as sequence1

Current Seed

# Get the current seed
current_seed = srand
puts current_seed  # => some integer

# Returns old seed when setting new one
old = srand(999)
puts old  # => previous seed

Game Development

# Deterministic game for replays
class Game
  def initialize(seed = Time.now.to_i)
    srand(seed)
    @enemy_positions = generate_enemies
  end
  
  def generate_enemies
    10.times.map { [rand(800), rand(600)] }
  end
end

# Same seed = same gameplay
game1 = Game.new(12345)
game2 = Game.new(12345)
# game1.enemy_positions == game2.enemy_positions

Modern Random (Ruby 1.9.2+)

# Ruby's modern Random class
rng = Random.new(12345)
rng.rand(10)  # => 7

# Or use Random::DEFAULT with srand
srand(42)
rand(100)

Important Notes

  • In Ruby 2.4+, rand without srand automatically seeds from SecureRandom
  • For security-sensitive randomness, use the securerandom gem
  • Setting seed 0 works same as any other seed

See Also