Developer Lab · Ruby
Generate UUID in Ruby
SecureRandom.uuid is built into Ruby's standard library since Ruby 1.9 - zero dependencies, CSPRNG-backed, returns a lowercase hyphenated string directly.
Quick Reference
| Method | Version | Sortable | Use Case |
|---|---|---|---|
| SecureRandom.uuid | v4 | No | General purpose - zero deps, built-in stdlib |
| UUIDTools::UUID.random_create | v4 | No | UUIDTools gem - also supports v3/v5 |
| UUIDTools::UUID.sha1_create | v5 | No | Deterministic - namespace + name |
Primary Implementation
require 'securerandom' # not needed in Rails - auto-required
# UUID v4 - random, CSPRNG-backed, returns lowercase string directly
id = SecureRandom.uuid
puts id
# → "f47ac10b-58cc-4372-a567-0e02b2c3d479"
# No hyphens
id_hex = SecureRandom.uuid.delete('-')
# → "f47ac10b58cc4372a5670e02b2c3d479"
# Uppercase
id_upper = SecureRandom.uuid.upcase
# → "F47AC10B-58CC-4372-A567-0E02B2C3D479"
# Generate multiple
ids = Array.new(5) { SecureRandom.uuid }
# Validate a UUID string
UUID_REGEX = /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\z/i
def valid_uuid?(str)
UUID_REGEX.match?(str)
end
puts valid_uuid?(id) # → trueAll UUID Versions
UUID v4 - Random (built-in stdlib)
require 'securerandom'
# Returns a lowercase hyphenated string - no object wrapping
id = SecureRandom.uuid
# → "550e8400-e29b-41d4-a716-446655440000"UUID v5 - Deterministic (UUIDTools gem)
# gem install uuidtools
require 'uuidtools'
# SHA-1 hash of namespace + name - same inputs always produce the same UUID
id = UUIDTools::UUID.sha1_create(UUIDTools::UUID_DNS_NAMESPACE, 'example.com')
puts id.to_s # → always "cfbff0d1-9375-5685-968c-48ce8b15ae17"Rails - ActiveRecord UUID primary key
# config/initializers/generators.rb
Rails.application.config.generators do |g|
g.orm :active_record, primary_key_type: :uuid
end
# db/migrate/20240101000000_create_users.rb
class CreateUsers < ActiveRecord::Migration[7.1]
def change
create_table :users, id: :uuid do |t|
t.string :name, null: false
t.timestamps
end
end
endReal-World Use Cases
1. Rails model with UUID primary key
class Order < ApplicationRecord
# Rails 7.1+ - use :uuid as primary key type in migration
# The model itself needs no changes - Rails handles UUID generation
before_create :set_public_id
private
def set_public_id
self.public_id ||= SecureRandom.uuid
end
end2. Sidekiq job ID
class ProcessOrderJob
include Sidekiq::Job
def perform(order_id)
# Sidekiq assigns its own JID, but you can add a correlation ID
correlation_id = SecureRandom.uuid
Rails.logger.tagged(correlation_id) do
order = Order.find(order_id)
order.process!
end
end
end3. API request tracing with Rack middleware
class RequestIdMiddleware
def initialize(app)
@app = app
end
def call(env)
request_id = SecureRandom.uuid
env['X-Request-ID'] = request_id
status, headers, body = @app.call(env)
headers['X-Request-ID'] = request_id
[status, headers, body]
end
end
# config/application.rb
config.middleware.use RequestIdMiddlewareCommon Mistakes
Using rand or object_id for IDs
rand is not CSPRNG-backed and object_id is a memory address - both are predictable and not unique across processes. Always use SecureRandom.uuid.
Not enabling UUID primary keys in Rails migrations
By default, Rails uses integer PKs. To use UUIDs, set id: :uuid in create_table and enable the pgcrypto extension in PostgreSQL (enable_extension 'pgcrypto').
Forgetting require 'securerandom' outside Rails
In plain Ruby scripts, SecureRandom is not auto-loaded. Add require 'securerandom' at the top. In Rails, it is auto-required.
How It Works
SecureRandom.uuid calls SecureRandom.random_bytes(16) internally, which maps to /dev/urandom on Linux/macOS and CryptGenRandom on Windows. It then sets the version (4) and variant bits per RFC 4122.
Unlike Java or Rust, Ruby returns a plain lowercase String directly - no wrapper object. This makes it easy to use but means there is no built-in UUID type for validation.
Output Formats
SecureRandom.uuid
f47ac10b-58cc-4372-a567-0e02b2c3d479
No hyphens
SecureRandom.uuid.delete('-')
Uppercase
SecureRandom.uuid.upcase
Best Practices, Performance, and Security
Best practices
Use SecureRandom.uuid for all new code - it's built-in and CSPRNG-backed.
In Rails, use id: :uuid in migrations and enable pgcrypto for PostgreSQL.
Validate incoming UUIDs with a regex before using them in queries.
Performance
Ruby generates roughly 1–2 million UUIDs/second. The bottleneck is the /dev/urandom syscall and string formatting.
For bulk generation, Array.new(n) { SecureRandom.uuid } is idiomatic. Avoid generating UUIDs in tight loops without batching DB inserts.
Security
Entropy source: /dev/urandom on Linux/macOS, CryptGenRandom on Windows. Cryptographically secure.
Suitable for session tokens, CSRF tokens, and API keys. Never use rand or Time.now.to_i for security-sensitive IDs.
Installation
UUID v4 (SecureRandom)
# No installation needed - stdlib since Ruby 1.9
require 'securerandom'In Rails, SecureRandom is auto-required. No Gemfile entry needed for basic UUID v4.
uuidtools gem (v3/v5)
gem install uuidtools # for v3/v5 supportOptional gem for deterministic v3/v5 UUID generation.
Frequently Asked Questions
How do I generate a UUID in Ruby?
SecureRandom.uuid from Ruby's standard library returns a cryptographically random v4 UUID after you require 'securerandom'. It is backed by the operating system CSPRNG. Ruby's stdlib has no v7 generator, so use a gem such as uuid7 if you need time-ordered identifiers.
Is SecureRandom.uuid cryptographically secure?
Yes. SecureRandom.uuid uses the platform CSPRNG (operating system secure random source), suitable for session tokens, API keys, and idempotency keys. Do not use non-cryptographic random sources for security-sensitive identifiers.
What is the difference between UUID v4 and v7 in Ruby?
UUID v4 (SecureRandom.uuid or equivalent) is fully random and not sortable. UUID v7 embeds a millisecond timestamp for chronological sorting (RFC 9562). Use v4 for general-purpose IDs; use v7 for database primary keys at scale.
Do I need to install a package for UUID generation in Ruby?
No additional package is required for basic v4 generation in Ruby. Check the Installation section for version-specific notes.
How do I validate a UUID string in Ruby?
Use the platform's UUID parse/validation function, or test against the RFC 4122 regex: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i. Always validate external input at API boundaries.
Should I use UUIDs as database primary keys in Ruby applications?
UUIDs work well as primary keys for distributed systems. Prefer native UUID/BINARY(16) column types over VARCHAR(36). For very large tables, consider UUID v7 for better B-tree insert locality.
Can I generate UUIDs in Ruby without a network connection?
Yes. UUID generation uses local OS entropy sources and does not require network access. Each call is independent and thread-safe on modern platforms.
What output formats are available in Ruby?
The standard hyphenated lowercase string (36 chars) is the default. Most APIs also support 32-char hex (no hyphens) and 16-byte binary formats. Use string format for APIs and binary for database storage.
What RFC standards apply to Ruby UUID generation?
Version 4 UUIDs follow RFC 4122. UUID v7 follows RFC 9562 (May 2024). Ensure your chosen method produces compliant version and variant bits.
When should I avoid UUID v1?
Avoid UUID v1 in security-sensitive contexts - it embeds MAC address and timestamp information. Prefer v4 (SecureRandom.uuid or equivalent) unless you need legacy Cassandra timeuuid compatibility.
Key definitions
- UUID
- 128-bit universally unique identifier, usually shown as 36 hex characters with hyphens.
- CSPRNG
- Cryptographically secure pseudo-random number generator - the entropy source behind secure UUID generation.
- RFC 4122
- IETF standard defining UUID versions 1 through 5. Version 4 is random.
- RFC 9562
- IETF standard adding UUID versions 6, 7, and 8. Version 7 is time-ordered.