Skip to content

UUID Generator — Ruby source

Generate RFC 4122 v4 UUIDs with crypto-grade randomness. Bulk generate, copy all, toggle format (uppercase / no hyphens).

This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.

# RFC 4122 v4 UUID generator (cryptographically secure).
#
# Language: Ruby (3.x, standard library)
# CosmoDev polyglot showcase port of the `uuid` tool.
# Ported from src/lib/uuid.ts — display source, part of CosmoDev's
# polyglot tool pages.
#
# Produces a random (v4) UUID: 36 characters, lowercase, hyphenated as
# 8-4-4-4-12 hex digits, with the RFC version (4) and variant (10xx)
# bits set. SecureRandom.bytes draws from the OS CSPRNG (OpenSSL
# RAND_bytes), so output is unpredictable and collision-safe.

require 'securerandom'

# Return a freshly generated RFC 4122 version-4 UUID string.
#
# Ruby ships SecureRandom.uuid as a one-liner; the explicit
# construction below mirrors the algorithm the TypeScript lib — and
# every other language in this polyglot set — implements, so the
# version/variant bit-stamping reads the same across all of them.
def uuid_v4
  raw = SecureRandom.bytes(16).unpack('C16')

  raw[6] = (raw[6] & 0x0f) | 0x40 # version 4: high nibble of byte 6
  raw[8] = (raw[8] & 0x3f) | 0x80 # variant  : high bits of byte 8

  hexed = raw.map { |b| format('%02x', b) }.join
  "#{hexed[0, 8]}-#{hexed[8, 4]}-#{hexed[12, 4]}-#{hexed[16, 4]}-#{hexed[20, 12]}"
end

puts uuid_v4

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →