How to generate a random string in Ruby -


i'm generating 8-character pseudo-random uppercase string "a" .. "z":

value = ""; 8.times{value  << (65 + rand(25)).chr} 

but doesn't clean, , can't passed argument since isn't single statement. mixed-case string "a" .. "z" plus "a" .. "z", changed to:

value = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr} 

but looks trash.

does have better method?

(0...8).map { (65 + rand(26)).chr }.join 

i spend time golfing.

(0...50).map { ('a'..'z').to_a[rand(26)] }.join 

and last 1 that's more confusing, more flexible , wastes fewer cycles:

o = [('a'..'z'), ('a'..'z')].map(&:to_a).flatten string = (0...50).map { o[rand(o.length)] }.join 

Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -