How to generate a UUID in Ruby
Ruby is a dynamic, open-source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. It was developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan. In Ruby, everything is an object, including primitive data types.
Generating a UUID in Ruby
Here is an example of how to generate a UUID in Ruby:
require 'securerandom'
guid = SecureRandom.uuid
puts guid This program uses the SecureRandom module to generate a random UUID and then prints it to the console. SecureRandom is part of Ruby's standard library, so you don't need to install it separately. You can use it in your Ruby program by simply requiring it at the top of your file with the line require 'securerandom'. This makes the SecureRandom module available for use in your program.
Explanation
- Line #1 loads the
SecureRandommodule from Ruby's standard library. This module provides methods for generating secure random numbers, UUIDs, and other random data. - Line #2 calls the
uuidmethod on the SecureRandom module to generate a random UUID (Universally Unique Identifier). The generated UUID is then assigned to theguidvariable. - Line #3 prints the value of the
guidvariable to the console. In this case, it will print the generated UUID.
How to format a 32-character string into a UUID in Ruby
In Ruby's standard library, UUIDs are typically represented as canonical strings generated by SecureRandom.uuid rather than a dedicated UUID class instance. If you have a 32-character hexadecimal string without hyphens, you can format it into canonical 8-4-4-4-12 UUID layout:
def format_as_uuid(string)
s = string.dup
s.insert(8, '-').insert(13, '-').insert(18, '-').insert(23, '-')
end
raw_string = "550e8400e29b41d4a716446655440000"
uuid = format_as_uuid(raw_string)
puts uuid # => "550e8400-e29b-41d4-a716-446655440000"Explanation
- Line #1 defines a method named
format_as_uuidthat accepts a 32-character hexadecimal string. - Line #2 uses
string.dupto create a copy, avoiding mutating the caller's input string in-place. - Line #3 chains Ruby's
insertmethod to place hyphens at character offsets 8, 13, 18, and 23. - Line #4 returns the canonical hyphenated UUID string.
- Lines #7-#9 test the method with a 32-character sample string and print the formatted UUID to the console.