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?
This solution needs external dependency, but seems prettier than another.
Faker::Lorem.characters(10) # => "ang9cbhoa8"
I think this is a nice balance of conciseness, clarity and ease of modification.
Easily modified
For example, including digits:
Uppercase hexadecimal:
For a truly impressive array of characters:
My favorite is
(:A..:Z).to_a.shuffle[0,8].join
. Note that shuffle requires Ruby > 1.9.I use this for generating random URL friendly strings with a guaranteed maximum length:
It generates random strings of lowercase a-z and 0-9. It's not very customizable but it's short and clean.
I spend too much time golfing.
And a last one that's even more confusing, but more flexible and wastes fewer cycles:
Since ruby 2.5 really easy with
SecureRandom.alphanumeric
:Generates random strings containing A-Z, a-z and 0-9 and therefore should be applicable in most use cases. And they are generated randomly secure, which might be a benefit, too.
Edit: A benchmark to compare it with the solution having the most upvotes:
So the
rand
solution only takes about 3/4 of the time ofSecureRandom
. Might matter if you generate really a lot of strings, but if you just create some random string from time to time I'd always go with the more secure implementation (since it is also easier to call and more explicit).