Skip to content

Instantly share code, notes, and snippets.

@rutvij-pandya
Created October 12, 2018 10:28
Show Gist options
  • Save rutvij-pandya/f9d2fb019ac5c7903068a657929d49d0 to your computer and use it in GitHub Desktop.
Save rutvij-pandya/f9d2fb019ac5c7903068a657929d49d0 to your computer and use it in GitHub Desktop.
Generate random alphanumeric string in Ruby (v < 2.5)
# Ruby(2.4.4) Module - SecureRandom - https://ruby-doc.org/stdlib-2.4.4/libdoc/securerandom/rdoc/SecureRandom.html
SecureRandom.class_eval do
CHARSET = [*"A".."Z", *"0".."9"]
# Returns Randomly generated 6 or more char long alphanumeric string
def self.alphanumeric(number)
CHARSET.sample(number).join
end
end
## Sample -
# Generate 6 chars long random alphanumeric string
# > SecureRandom.alphanumeric(6)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment