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

Generate UUIDs in Ruby

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: Ruby

What: Generate UUIDs in Ruby using the built-in <code>SecureRandom.uuid</code> method. No gems required for basic UUID v4 generation.

Try it: Use our interactive Uuids generator or integrate this code into your Ruby application.

Generate UUIDs in Ruby using the built-in SecureRandom.uuid method. No gems required for basic UUID v4 generation. 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'

# UUID v4 (random)
uuid = SecureRandom.uuid
puts uuid  # Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f

# Generate multiple UUIDs
5.times do
  puts SecureRandom.uuid
end

# Using UUIDTools gem for more features (gem install uuidtools)
require 'uuidtools'

# UUID v4
uuid4 = UUIDTools::UUID.random_create
puts uuid4.to_s  # Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f

# UUID v5 (namespaced)
namespace = UUIDTools::UUID_DNS_NAMESPACE
name = 'example.com'
uuid5 = UUIDTools::UUID.sha1_create(namespace, name)
puts uuid5.to_s  # Always same: cfbff0d1-9375-5685-968c-48ce8b15ae17

# Parse UUID from string
uuid_string = '3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f'
parsed = UUIDTools::UUID.parse(uuid_string)
puts parsed.valid?  # Outputs: true

# In Rails models (ActiveRecord)
# class User < ApplicationRecord
#   before_create :generate_uuid
#
#   private
#   def generate_uuid
#     self.id = SecureRandom.uuid
#   end
# end

[EXPLANATION]

SecureRandom.uuid is built into Ruby (no gems needed). For advanced features like UUID v5 and validation, use the uuidtools gem. In Rails, you can use UUID columns in PostgreSQL with native support.

Expected Output

3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f
cfbff0d1-9375-5685-968c-48ce8b15ae17
true

Common Use Cases

  • Ruby on Rails model primary keys
  • Devise gem user identifiers
  • Sidekiq job IDs
  • PostgreSQL UUID columns
  • API request tracking
  • Sinatra application session IDs

Important Notes

  • SecureRandom.uuid is cryptographically secure
  • Rails 4+ has built-in UUID support for PostgreSQL
  • uuidtools gem provides more UUID versions
  • No need to add gems for basic UUID v4 generation

Try Our Interactive Generator

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

TRY UUIDS GENERATOR →