Generate Random Passwords in Ruby
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: Ruby
What: Generate secure random passwords in Ruby using <code>SecureRandom</code> for cryptographically secure random generation. Perfect for Ruby on Rails applications.
Try it: Use our interactive Passwords generator or integrate this code into your Ruby application.
Generate secure random passwords 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_password(length = 16, include_special = true)
lowercase = ('a'..'z').to_a
uppercase = ('A'..'Z').to_a
numbers = ('0'..'9').to_a
special = '!@#$%^&*()-_=+[]{}|;:,.<>?'.chars
chars = lowercase + uppercase + numbers
chars += special if include_special
Array.new(length) { chars[SecureRandom.random_number(chars.length)] }.join
end
# Generate a 16-character password with special characters
password = generate_password(16, true)
puts password # Example: aB3$xY7!mN2@pQ9&
# Generate a 12-character password without special characters
simple_password = generate_password(12, false)
puts simple_password # Example: aB3xY7mN2pQ9
[EXPLANATION]
SecureRandom.random_number provides cryptographically secure random integers. This implementation uses Ruby's array and string manipulation methods for clean, idiomatic code.
Expected Output
aB3$xY7!mN2@pQ9& aB3xY7mN2pQ9
Common Use Cases
- Ruby on Rails user authentication
- Devise gem password reset functionality
- Sinatra web application security
- API token generation for REST APIs
- Background job systems (Sidekiq, Resque)
- Command-line tools and scripts
Important Notes
-
SecureRandomis cryptographically secure - Available in Ruby standard library (no gems needed)
-
Use
SecureRandom.urlsafe_base64for URL-safe tokens -
Rails has built-in
SecureRandomsupport
Try Our Interactive Generator
Don't want to write code? Use our free web-based Passwords generator with instant results.
TRY PASSWORDS GENERATOR →Other Programming Languages
View Passwords generation code examples in PHP
View Passwords generation code examples in JavaScript
View Passwords generation code examples in Python
View Passwords generation code examples in Java
View Passwords generation code examples in C#
View Passwords generation code examples in C++
View Passwords generation code examples in Go