-
-
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..
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
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
line 19 should be:
to accommodate Ranges and individual characters being specified, e.g.:
base64 random number: