Ruby Tuesday – SecureRandom::uuid

Today’s Ruby Tuesday is on SecureRandom::uuid.

Sometimes you just want a unique identifier, and the more guaranteed to be unique the identifier is, the better.

Enter SecureRandom::uuid.

SecureRandom::uuid generates a new 128 bit identifier, and according to the RFC for a UUID, a.k.a GUID, is “guaranteed to be unique across space and time”.

While the math and avanced physics to prove that guarantee is beyond me, I have found that they are unqiue enough for every case that I have encountered so far. If you find otherwise I would love for you to let me know how you “broke” that guarantee.

To use SecureRandom::uuid, we first have to require 'securerandom'. And yes, this is one of those Ruby requires that does not have the name snake cased, but all one word.

require 'securerandom'
# => true
# => "fc804c3a-def2-4739-a723-605992f055cc"
# => "67986323-afe9-41c9-81d8-c91d13593534"
# => "2deabd2c-55a1-48b5-8b6e-6ee96d56036e"
# => String

This returns a Version 4 UUID, as can be seen by the 4 following the second dash in the UUID.

# => String

Be warned though, that this doesn’t generate an actual UUID object, but just the String representation of a UUID, so if you need access to the raw bits of the UUID generated, you will likely need to track down another gem for that use case.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.