I'm currently generating an 8-character pseudo-random uppercase string for "A" .. "Z":
value = ""; 8.times{value << (65 + rand(25)).chr}
but it doesn't look clean, and it can't be passed as an argument since it isn't a single statement. To get a mixed-case string "a" .. "z" plus "A" .. "Z", I changed it to:
value = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr}
but it looks like trash.
Does anyone have a better method?
Just adding my cents here...
If you want a string of specified length, use:
It will generate a random string of length
2n
containing0-9
anda-f
Be aware:
rand
is predictable for an attacker and therefore probably insecure. You should definitely use SecureRandom if this is for generating passwords. I use something like this:you can use
String#random
from the Facets of Ruby Gemfacets
:https://github.com/rubyworks/facets/blob/126a619fd766bc45588cac18d09c4f1927538e33/lib/core/facets/string/random.rb
it basically does this: