Generate Random Strings in Ruby
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: Ruby
What: Generate random strings in Ruby using <code>SecureRandom</code> for cryptographically secure random generation. Perfect for Ruby on Rails applications.
Try it: Use our interactive Strings generator or integrate this code into your Ruby application.
Generate random strings in Ruby using SecureRandom for cryptographically secure random generation. Perfect for Ruby on 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'
def generate_random_string(length = 16, custom_chars = nil)
chars = custom_chars || ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
Array.new(length) { chars[SecureRandom.random_number(chars.length)] }.join
end
# Generate a 16-character alphanumeric string
random_string = generate_random_string(16)
puts random_string # Example: aB3xY7mN2pQ9zR5t
# Generate a 12-character hex string
hex_string = generate_random_string(12, ('0'..'9').to_a + ('a'..'f').to_a)
puts hex_string # Example: a3f7b2e9c4d1
# Generate a 10-character lowercase string
lowercase_string = generate_random_string(10, ('a'..'z').to_a)
puts lowercase_string # Example: xmkpqrstuv
# Alternative: use built-in methods
hex_token = SecureRandom.hex(8) # 16 hex characters
puts hex_token
urlsafe_token = SecureRandom.urlsafe_base64(12)
puts urlsafe_token
[EXPLANATION]
SecureRandom.random_number provides cryptographically secure random integers. This implementation uses Ruby's idiomatic array and string methods. Built-in methods like SecureRandom.hex() and SecureRandom.urlsafe_base64() offer convenient alternatives.
Expected Output
aB3xY7mN2pQ9zR5t a3f7b2e9c4d1 xmkpqrstuv a3f7b2e9c4d1f8a6 xK8mP2vN5qR7sT9w
Common Use Cases
- Ruby on Rails session token generation
- Devise gem authentication tokens
- Sinatra web application IDs
- API key and secret generation
- Active Record unique identifiers
- Background job tracking IDs
Important Notes
-
SecureRandomis cryptographically secure -
SecureRandom.hex(n)generates 2n hex characters -
SecureRandom.urlsafe_base64()for URL-safe strings - Available in Ruby standard library (no gems needed)
Try Our Interactive Generator
Don't want to write code? Use our free web-based Strings generator with instant results.
TRY STRINGS GENERATOR →Other Programming Languages
View Strings generation code examples in PHP
View Strings generation code examples in JavaScript
View Strings generation code examples in Python
View Strings generation code examples in Java
View Strings generation code examples in C#
View Strings generation code examples in C++
View Strings generation code examples in Go