Developer Tools for Random Data Generation // v2.5.1
root@generate-random:~/passwords/ruby$ _

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

  • SecureRandom is cryptographically secure
  • Available in Ruby standard library (no gems needed)
  • Use SecureRandom.urlsafe_base64 for URL-safe tokens
  • Rails has built-in SecureRandom support

Try Our Interactive Generator

Don't want to write code? Use our free web-based Passwords generator with instant results.

TRY PASSWORDS GENERATOR →