Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating GUIDs in Ruby

Tags:

guid

ruby

People also ask

How do you generate GUIDs?

To Generate a GUID in Windows 10 with PowerShell, Type or copy-paste the following command: [guid]::NewGuid() . This will produce a new GUID in the output. Alternatively, you can run the command '{'+[guid]::NewGuid(). ToString()+'}' to get a new GUID in the traditional Registry format.

What is UUID in Ruby?

Ruby | Random uuid() function Random#uuid() : uuid() is a Random class method which checks returns a random v4 UUID (Universally Unique IDentifier). Syntax: Random.uuid() Parameter: Random values. Return: a random v4 UUID (Universally Unique IDentifier).

How many GUIDs can be generated?

However, you can try to calculate the chance of creating two GUIDs that are identical and you get the idea: a GUID has 128 bits, hence, there are 2128 distinct GUIDs – much more than there are stars in the known universe.


As of Ruby 1.9, uuid generation is built-in. Use the SecureRandom.uuid function.

For example:

require 'securerandom'
SecureRandom.uuid # => "96b0a57c-d9ae-453f-b56f-3b154eb10cda"

How to create small, unique tokens in Ruby

>> require 'digest'
=> []
>> Digest::SHA1.hexdigest("some-random-string")[8..16]
=> "2ebe5597f"

>> SecureRandom.base64(8).gsub("/","_").gsub(/=+$/,"")
=> "AEWQyovNFo0" 

>> rand(36**8).to_s(36)
=> "uur0cj2h"

Did you look at UUIDTools?

UUIDTools was designed to be a simple library for generating any of the various types of UUIDs (or GUIDs if you prefer to call them that). It conforms to RFC 4122 whenever possible.


Google yields the following Ruby library:

http://raa.ruby-lang.org/project/ruby-guid/

Also, over at http://www.ruby-forum.com/topic/99262 they say you can install a gem (execute gem uuid on the command line to install it) and then do

gem 'uuid'
puts UUID.new

in your code to see a new UUID.

(Hint: I Googled for guid ruby)


To create a proper, mysql, varchar 32 GUID

SecureRandom.uuid.gsub('-','').upcase

Small update to Simone Carletti answer:

SecureRandom.base64(8).gsub("/","_").gsub(/=+$/,"")

=> "AEWQyovNFo0"

can be replaced with:

SecureRandom.urlsafe_base64(8)