-
-
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's another version of this, with pre-computed character sets: