Generate Random number in ruby using SecureRandom

Ruby 1.9.x includes a lot of new things and one of the coolest things is the SecureRandom.

SecureRandom has useful methods for creating random numbers and strings. Some useful methods are described below

SecureRandom#base64

The result will contain A-Z, a-z, 0-9, “+”, “/” and “=”. If we will not provide the length of the string it will take 16 as default.

If the SecureRandom number generator will through “NotImplementedError” then you need to include “require ‘securerandom'”

p SecureRandom.base64 #pNPkWt2SaoHAqlMzFxSG4w==
p SecureRandom.base64(8) #Vi7OjnZYdW0=
p SecureRandom.base64(4) #JgPjpQ==

SecureRandom#hex

The result will be alphanumeric and contain 0-9 and a-f. If we will not provide the length of the string it will take 16 as default.
The length of the string will be the twice of n.

p SecureRandom.hex #8aecb22ea5388614f440b73ddf1ab458
p SecureRandom.hex(4) #87bef884

SecureRandom#random_number

The result will be the numeric only and contant 0-9. If we will not provide the argument then the result will be float

p SecureRandom.random_number #0.6153820461378544
p SecureRandom.random_number(100) #46

SecureRandom#uuid()

It will generate a v4 random UUID (Universally Unique IDentifier) is pure unique across a large namespace for universal unique number to generate a ID in a database.

p SecureRandom.uuid #215eb865-681f-4afa-b995-796b1e74299b

SecureRandom#urlsafe_base64

It will generate the random URL-safe token and contain A-Z, a-z, 0-9, “-” and “_”. “=” is also used if padding is true. If we will not provide the length of the string it will take 16 as default.

By default, padding is not generated because “=” may be used as a URL delimiter.

The generated string is not as unique as one generated by UUID, it will still be fairly random. Guaranteeing uniqueness across an application with a small loop.

The resulting string only includes characters that are URL safe

p SecureRandom.urlsafe_base64 #_TpR098Z46M7nuvQ_AkKUQ
p SecureRandom.urlsafe_base64(nil, true) #MHTSlDPU15fk66ZD6x6LLg==