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 SecureRandom.uuid # => "fc804c3a-def2-4739-a723-605992f055cc" SecureRandom.uuid # => "67986323-afe9-41c9-81d8-c91d13593534" SecureRandom.uuid # => "2deabd2c-55a1-48b5-8b6e-6ee96d56036e" SecureRandom.uuid.class # => String
This returns a Version 4 UUID, as can be seen by the 4
following the second dash in the UUID.
SecureRandom.uuid.class # => 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.
–Proctor