How best to generate a random string in Ruby

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I m currently using the following to generate an 8 character pseudo random upper case string [A-Z]

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

but it looks junky, and since it isn t a single statement it can t be passed as an argument. To get a mixed case string [a-zA-Z] I further hack into it with

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

Just looks like trash. Anyone have a better method?

Answers

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

I spend too much time golfing.

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

And a last one that s even more confusing, but more flexible and wastes fewer cycles:

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

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/88311/how-best-to-generate-a-random-string-in-ruby

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils