Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awesome/4846fc6d9283936f7a0dd12a17d25b99 to your computer and use it in GitHub Desktop.
Save awesome/4846fc6d9283936f7a0dd12a17d25b99 to your computer and use it in GitHub Desktop.
Ruby SecureRandom fake string of alphanumeric characters; always lead with alphabetic characters.
#
# "generate a string with 0-9a-z (36 characters) that is ALWAYS 12 characters long. Change 12 to whatever length you want."
# -- Gerry Shaw via https://stackoverflow.com/questions/88311/how-to-generate-a-random-string-in-ruby#comment35392122_1619602
#
# min length is 6
def fake_code(length = 12)
# always lead with four chars
str = SecureRandom.hex.gsub(/\d/, "")[0..3]
# followed by chars or int
str << SecureRandom.random_number(36**12).to_s(36).rjust(12, "0")[0..(length-5)]
end
# SecureRandom.hex.partition(/.{16}\z/)[0..1]
# => ["1e409ee9d1d0c2ca", "03968cd52870b79a"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment