How to Generate UUID in Ruby

Ruby provides built-in support for generating RFC 4122 compliant UUIDs using the SecureRandom module. This guide covers all methods for generating and working with UUIDs in Ruby.

1. Using SecureRandom (Standard Library)

The simplest way to generate a UUID v4 using Ruby's built-in library.

require 'securerandom'

# Generate UUID v4
uuid = SecureRandom.uuid
puts uuid
# Output: "550e8400-e29b-41d4-a716-446655440000"

# Generate multiple UUIDs
5.times { puts SecureRandom.uuid }

2. Using the uuid Gem

For UUID v1 (timestamp-based) or more control over UUID generation.

# Install the gem
gem install uuid
require 'uuid'

# Create a UUID generator
generator = UUID.new

# Generate UUID v1 (time-based)
uuid_v1 = generator.generate
puts uuid_v1  # "2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d"

# Generate UUID v4 (random)
uuid_v4 = generator.generate(:random)
puts uuid_v4

3. UUID Validation

def valid_uuid?(uuid)
  uuid_regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
  !!(uuid =~ uuid_regex)
end

puts valid_uuid?("550e8400-e29b-41d4-a716-446655440000")  # true
puts valid_uuid?("not-a-uuid")                            # false
puts valid_uuid?("550E8400-E29B-41D4-A716-446655440000")  # true (case insensitive)

4. UUID Formatting

require 'securerandom'

uuid = SecureRandom.uuid
# "550e8400-e29b-41d4-a716-446655440000"

# Remove hyphens
compact = uuid.delete('-')
puts compact  # "550e8400e29b41d4a716446655440000"

# Uppercase
uppercase = uuid.upcase
puts uppercase  # "550E8400-E29B-41D4-A716-446655440000"

# Add hyphens to compact UUID
def format_uuid(compact)
  [
    compact[0..7],
    compact[8..11],
    compact[12..15],
    compact[16..19],
    compact[20..31]
  ].join('-')
end

puts format_uuid("550e8400e29b41d4a716446655440000")
# "550e8400-e29b-41d4-a716-446655440000"

5. Rails UUID Support

Rails has built-in UUID support for database primary keys.

# In migration - use UUID as primary key
class CreateUsers < ActiveRecord::Migration[7.0]
  def change
    create_table :users, id: :uuid do |t|
      t.string :name
      t.string :email
      t.timestamps
    end
  end
end

# Or add UUID column
class AddUuidToProducts < ActiveRecord::Migration[7.0]
  def change
    add_column :products, :public_id, :uuid, default: 'gen_random_uuid()'
  end
end
# In model - auto-generate UUID
class User < ApplicationRecord
  before_create :set_uuid

  private

  def set_uuid
    self.id = SecureRandom.uuid
  end
end

# Or use Rails built-in
class Product < ApplicationRecord
  # For PostgreSQL with pgcrypto extension
  # id is automatically generated as UUID
end

6. Bulk UUID Generation

require 'securerandom'

# Generate array of UUIDs
def generate_uuids(count)
  Array.new(count) { SecureRandom.uuid }
end

uuids = generate_uuids(10)
puts uuids.join("
")

# Generate unique UUIDs to a file
File.open('uuids.txt', 'w') do |file|
  1000.times { file.puts SecureRandom.uuid }
end

7. UUID to Binary and Back

require 'securerandom'

uuid = SecureRandom.uuid
# "550e8400-e29b-41d4-a716-446655440000"

# Convert to binary (16 bytes)
binary = [uuid.delete('-')].pack('H*')
puts binary.bytesize  # 16

# Convert binary back to UUID
hex = binary.unpack1('H*')
formatted = "#{hex[0..7]}-#{hex[8..11]}-#{hex[12..15]}-#{hex[16..19]}-#{hex[20..31]}"
puts formatted  # "550e8400-e29b-41d4-a716-446655440000"

8. Extract UUID Version

def uuid_version(uuid)
  # Version is the first character of the third group
  version_char = uuid.split('-')[2][0]
  version_char.to_i
end

puts uuid_version("550e8400-e29b-41d4-a716-446655440000")  # 4
puts uuid_version("2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d")  # 1

Best Practices

  • Use SecureRandom.uuid for most use cases (UUID v4)
  • Use the uuid gem when you need UUID v1 (timestamp-based)
  • In Rails, use native UUID support with PostgreSQL
  • Store UUIDs as binary (16 bytes) for better database performance
  • Validate UUIDs before using them in queries
  • Use SecureRandom over Random for cryptographic security

Ready to use what you learned?

Try UUID Generator now