Skip to main content

How to Generate UUID in Ruby

Using SecureRandom.uuid

Ruby ships everything you need to generate a UUID without installing a single gem: the SecureRandom module's uuid method hands back a random, cryptographically secure UUID string in one line. There's no dedicated UUID class in Ruby's standard library, so that string is exactly what you get — ready to drop straight into session tokens, API keys, or a database primary key. Below you'll find copy-paste ready code for generating a UUID in Ruby, validating that a string is a properly formatted UUID, and the third-party options available when SecureRandom's v4-only output isn't enough. Use the c# uuid guide to implement GUID primary keys in Entity Framework Core with optimal SQL Server performance.

Generate UUID in Ruby

SecureRandom.uuid
550e8400-e29b-41d4-a716-446655440000

How to Generate a UUID in Ruby

The simplest way to generate a UUID in Ruby is SecureRandom.uuid, built into the standard library's securerandom module — no gem install required. It returns a random, RFC 4122-compliant version 4 UUID as a plain String.

main.rb
require 'securerandom'

my_uuid = SecureRandom.uuid
puts my_uuid
# Output: 550e8400-e29b-41d4-a716-446655440000

Explanation

Convert a String to a UUID in Ruby

Ruby's standard library treats UUIDs as plain strings, so there's no dedicated type to convert a string into — what you actually need is to confirm a string is a well-formed UUID before you trust it. A regular expression handles that in one line. The rust uuid generator guide includes type-safe newtype wrappers, serde integration, and Diesel column definitions.

main.rb
UUID_REGEX = /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i

def valid_uuid?(str)
  UUID_REGEX.match?(str)
end

valid_uuid?("550e8400-e29b-41d4-a716-446655440000") # true
valid_uuid?("not-a-uuid")                            # false

Explanation

Other Options for Generating UUIDs in Ruby

SecureRandom.uuid only generates version 4 (random) UUIDs. For version 1, 3, or 5 identifiers, or a dedicated UUID object type instead of a plain string, reach for the third-party uuid gem.

Gemfile
gem 'uuid'
main.rb
require 'uuid'

# Random / timestamp-based UUID
uuid = UUID.generate
# UUID.generate also supports namespace-based (v3/v5-style) identifiers

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!