Generate Random Numbers in Ruby
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: Ruby
What: Generate random numbers in Ruby using <code>rand()</code> for general purposes or <code>SecureRandom</code> for cryptographically secure random numbers in Ruby and Rails applications.
Try it: Use our interactive Numbers generator or integrate this code into your Ruby application.
Generate random numbers in Ruby using rand() for general purposes or SecureRandom for cryptographically secure random numbers in Ruby and Rails applications.
Looking for other languages? Check our code examples in
PHP
,
JavaScript
,
Python
,
Java
,
C#
,
C++
and
Go
or use our interactive web generator.
Ruby Code Example
require 'securerandom'
# Generate a single random number between 1 and 100
random_number = rand(1..100)
puts random_number # Example output: 42
# Generate multiple random numbers
numbers = Array.new(10) { rand(1..100) }
puts numbers.inspect
# Example output: [23, 7, 91, 45, 12, 68, 3, 89, 54, 31]
# Generate cryptographically secure random number
secure_number = SecureRandom.random_number(1..100)
puts secure_number # Example: 67
# Random float between 0 and 100
random_float = rand(0.0..100.0)
puts format('%.2f', random_float) # Example: 42.17
# Using Random class for reproducible results
prng = Random.new(42) # Seeded for reproducibility
seeded_number = prng.rand(1..100)
puts seeded_number
[EXPLANATION]
rand(range) generates random numbers within a range. SecureRandom provides cryptographically secure random numbers suitable for security tokens and keys. The Random class allows seeded random generation for reproducible results.
Expected Output
42 [23, 7, 91, 45, 12, 68, 3, 89, 54, 31] 67 42.17
Common Use Cases
- Ruby on Rails application development
- API token and session key generation
- Test data generation for RSpec tests
- Rake task automation with random data
- Background job randomization (Sidekiq)
- Game logic and procedural generation
Important Notes
-
rand(n)generates 0 to n-1,rand(min..max)for ranges -
Use
SecureRandomfor passwords, tokens, and keys -
Random.new(seed)creates reproducible random sequences -
Available in Ruby 1.9+ (older versions use
Kernel.rand)
Try Our Interactive Generator
Don't want to write code? Use our free web-based Numbers generator with instant results.
TRY NUMBERS GENERATOR →Other Programming Languages
View Numbers generation code examples in PHP
View Numbers generation code examples in JavaScript
View Numbers generation code examples in Python
View Numbers generation code examples in Java
View Numbers generation code examples in C#
View Numbers generation code examples in C++
View Numbers generation code examples in Go