UUID
Generate and parse Universally Unique Identifiers (UUIDs). Supports UUID versions 4 (random) and 7 (timestamp-based).
import Encoding.UUID
Generation
UUID.v4
() -> String
Generate a random UUID version 4. Uses cryptographically secure random bytes.
id = UUID.v4()
# "550e8400-e29b-41d4-a716-446655440000"
UUID.v7
() -> String
Generate a timestamp-based UUID version 7. Includes millisecond timestamp for
time-ordered sorting. Ideal for database primary keys.
id = UUID.v7()
# "01932c19-8e80-7def-8c8a-5b6d43a2c1e0"
# UUIDs generated later sort after earlier ones
id1 = UUID.v7()
id2 = UUID.v7()
# id1 < id2 (lexicographically)
UUID.nil
() -> String
Get the nil UUID (all zeros). Useful as a placeholder or null value.
null-id = UUID.nil()
# "00000000-0000-0000-0000-000000000000"
Validation
UUID.valid?
String -> Bool
Check if a string is a valid UUID format. Accepts both with and without hyphens,
case insensitive.
UUID.valid? "550e8400-e29b-41d4-a716-446655440000" # true
UUID.valid? "550E8400E29B41D4A716446655440000" # true
UUID.valid? "not-a-uuid" # false
Parsing
UUID.parse
String -> Option a
Parse a UUID and extract its components: version, variant, and timestamp (for v7).
Returns
None for invalid UUIDs.
match UUID.parse "01932c19-8e80-7def-8c8a-5b6d43a2c1e0"
| Some info ->
println "Version: ${info.version}" # 7
println "Variant: ${info.variant}" # "RFC 4122"
| None -> println "Invalid UUID"
UUID v4 vs v7
| Property | v4 (Random) | v7 (Timestamp) |
|---|---|---|
| Uniqueness | Random 122 bits | Timestamp + random |
| Sortable | No | Yes (chronological) |
| DB Indexing | Poor (random) | Excellent (sequential) |
| Use Case | Session IDs, tokens | Primary keys, event IDs |