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.
require 'securerandom'
my_uuid = SecureRandom.uuid
puts my_uuid
# Output: 550e8400-e29b-41d4-a716-446655440000
Explanation
require 'securerandom'loads Ruby's built-in SecureRandom module — nogem installrequired.SecureRandom.uuidgenerates a random UUID (version 4) using a cryptographically secure random source under the hood.- The return value is a plain
String, not a dedicated UUID type — Ruby's standard library has noUUIDclass to wrap it in. puts my_uuidprints the standard 36-character hyphenated format directly, since it's already a string.
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.
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
UUID_REGEXmatches the 8-4-4-4-12 hexadecimal pattern every UUID follows, regardless of version or variant bits.- The
iflag makes the match case-insensitive, so both upper and lowercase hex digits pass. match?returns a boolean without allocating aMatchDataobject, which is faster than=~when you only need true or false.- Anchor with
\Aand\zrather than^and$— the latter can be tricked by embedded newlines in multi-line strings.
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.
gem 'uuid'
require 'uuid'
# Random / timestamp-based UUID
uuid = UUID.generate
# UUID.generate also supports namespace-based (v3/v5-style) identifiers
Explanation
- The
uuidgem is a separate library (gem install uuid) — not part of Ruby's standard library likeSecureRandom. UUID.generateproduces a UUID by default and also supports namespace-based generation for deterministic, name-derived identifiers.- Unlike
SecureRandom.uuid, the gem exposes UUID versions beyond v4, which matters if you need sortable or reproducible IDs. - On Rails, you don't need this gem just for primary keys —
create_table :users, id: :uuidin a migration generates UUID IDs automatically.