Skip to content

Instantly share code, notes, and snippets.

@tilo
Last active April 12, 2017 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tilo/3ee8d94871d30416feba to your computer and use it in GitHub Desktop.
Save tilo/3ee8d94871d30416feba to your computer and use it in GitHub Desktop.
Create a random String of given length, using given character setthis can come in handy for generating random strings, passwords, hex string, etc..
# Create a random String of given length, using given character set
#
# this can come in handy for generating random strings, passwords, hex string, etc..
#
# Usage / Examples:
# > String.random
# => "D9DxFIaqR3dr8Ct1AfmFxHxqGsmA4Oz3"
# > String.random(10)
# => "t8BIna341S"
# > String.random(10, ['a'..'z'])
# => "nstpvixfri"
# > String.random(10, ['0'..'9'] )
# => "2982541042"
# > String.random(10, ['0'..'9','A'..'F'] )
# => "3EBF48AD3D"
#
class String
def self.random(len=32, character_set = ["A".."Z", "a".."z", "0".."9"])
characters = character_set.map{|i| i.is_a?(Range) ? i.to_a : i }.flatten
characters_len = characters.length
(0...len).map{ characters[rand(characters_len)] }.join
end
end
@tilo
Copy link
Author

tilo commented Aug 14, 2015

line 19 should be:

     character_set.map{|i| i.is_a?(Range) ? i.to_a : i }.flatten

to accommodate Ranges and individual characters being specified, e.g.:

base64 random number:

     > BASE64_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", '_', '-'] 
     > String.random(10, BASE64_CHAR_SET)
      => "xM_1t3qcNn"

     > SPECIAL_CHARS = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+", "|", "/", "?", ".", ",", ";", ":", "~", "`", "[", "]", "{", "}", "<", ">"]
     > BASE91_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", SPECIAL_CHARS] 
     > String.random(10, BASE91_CHAR_SET)
      => "S(Z]z,J{v;"

@tilo
Copy link
Author

tilo commented Apr 12, 2017

Here's another version of this, with pre-computed character sets:

class String

  CHARACTER_SET = {
    :hex => ['0'..'9','A'..'F'],
    :alpha => ['a'..'z'],
    :alpha_numeric => ['a'..'z', 'A'..'Z', '0'..'9'],
    :base64 => ["A".."Z", "a".."z", "0".."9", '_', '-'],
    :special => ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+", "|", "/", "?", ".", ",", ";", ":", "~", "`", "[", "]", "{", "}", "<", ">"],
  }
  CHARACTER_SET[:base91] = [ CHARACTER_SET[:alpha_numeric] , CHARACTER_SET[:special] ].flatten

  # pre-compute which characters are in each character set
  chars = Hash.new
  CHARACTER_SET.each do |name, char_set|
    chars[name] = char_set.map{|x| x.is_a?(Range) ? x.to_a : x }.flatten
  end
  CHARS = chars.freeze


  def self.random(len=20, character_set_name= :alpha_numeric)
     Array.new(len){ String::CHARS[ character_set_name.to_sym ].sample }.join
  end

end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment