Generate a UUID in Ruby
Ruby is a popular, interpreted, dynamically typed, object-oriented programming language.
First created in 1993 by Matz, Ruby is a true object-oriented, general-purpose language and as such is used in a wide range of contexts. However, Ruby is most famously known for building dynamic websites in conjunction with the Ruby on Rails framework.
How to Generate a UUID in Ruby
The Ruby language has built-in support for generating Version 4 UUIDs. Here's an example of how you can create a UUID in Ruby code.
require 'securerandom'uuid = SecureRandom.uuidputs 'Your UUID is: ' + uuid
- On line #1, we require the
securerandomlibrary that is part of the Ruby standard library. The require give us access to the
- Line #3 generates a new UUID using the
SecureRandommodule and stores it in the variable,
- The output from line #5 will be something like:
Your UUID is: fc10b881-d9a0-4ab1-a6fd-a102db188f49
Other Options for Generating UUIDs in Ruby
In addition to the
SecureRandom module, the are many other options for generating UUIDs in Ruby.
For example, you can use the
UUIDTools Gem to
generate version 1 UUIDs:
### In your Gemfile ###gem 'uuidtools'### In your Ruby code ###require 'uuidtools'# Version 1 UUIDuuid = 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 UUIDuuid = Digest::UUID.uuid_v3(Digest::UUID::DNS_NAMESPACE, 'www.uuidgenerator.net')# Version 5 UUIDuuid = Digest::UUID.uuid_v5(Digest::UUID::DNS_NAMESPACE, 'www.uuidgenerator.net')
How can we improve this page? Let us know!