Generate a UUID in Ruby

Ruby, a popular interpreted, dynamically typed, and object-oriented programming language, offers built-in support for generating Version 4 UUIDs. In this comprehensive guide, we will explore different methods to generate UUIDs in Ruby.

How to Generate a UUID in Ruby

Ruby's securerandom library provides functions to generate Version 4 UUIDs. Let's start with an example of generating a UUID using Ruby code:

require 'securerandom'
 
uuid = SecureRandom.uuid
 
puts 'The UUID is: ' + uuid

Explanation

  • On line #1, we require the securerandom library that is part of the Ruby standard library. The require give us access to the SecureRandom module.
  • Line #3 generates a new UUID using the SecureRandom module and stores it in the variable, uuid.
  • The output from line #5 will be something like:
The UUID is: 119D2163-F16A-47AF-9DF7-418D3AF1455A

Other Options for Generating UUIDs in Ruby

In addition to the SecureRandom module, there are many other options for generating UUIDs in Ruby.

For example, you can use the UUIDTools gem to generate Version 1 UUIDs:

gem 'uuidtools'
require 'uuidtools'
 
# Version 1 UUID
uuid = UUIDTools::UUID.timestamp_create.to_s

If you're developing a Ruby on Rails app, you can also use ActiveSupport's Digest::UUID module to generate Version 3 and Version 5 UUIDs:

require 'activesupport/core_ext/digest/uuid'
 
# Version 3 UUID
uuid = Digest::UUID.uuid_v3(Digest::UUID::DNS_NAMESPACE, 'www.uuid.site')
 
# Version 5 UUID
uuid = Digest::UUID.uuid_v5(Digest::UUID::DNS_NAMESPACE, 'www.uuid.site')

To generate Version 7 UUIDs, you can use the UUID7 gem:

### In your Gemfile ###
gem 'uuid7'
 
### In your Ruby code ###
require 'uuid7'
 
# Version 7 UUID
uuid = UUID7.generate

Conclusion

Generating UUIDs in Ruby is made easy with the various options available, such as the securerandom library, UUIDTools gem, ActiveSupport's Digest::UUID module, and the UUID7 gem. By following the examples and explanations provided in this guide, you can generate unique identifiers for your Ruby applications.

Remember to choose the UUID version that fits your requirements and explore the capabilities of the selected method or gem for additional functionality. Happy coding with Ruby and UUID generation!