Generate a random hex

07 August 2017

  • ruby
  • hex
  • random
DESCRIPTION: a brief note on how to generate a random hex.



I have occasionally wanted to create a random security hex, when not using built-in rails methods. I wrote the following method to generate a 12 digit random hex, which was written to generate a random UUID for a FactoryGirl / RSpec test.

def gen_random_uuid { |char| [ ("a".."z").to_a[rand(26)], rand(10) ][rand(2)]}.join(",").gsub(",","")

I have never used the rails method before, but I understand it does essentially the same thing:

def gen_random_uuid

This generates a random 12 digit string.

Other methods with SecureRandom:

[ SecureRandom.hex, SecureRandom.base64, SecureRandom.random_bytes, SecureRandom.uuid ]

To use outside of rails put the following at the top of the ruby file:

require 'securerandom'