How to make a random string in Ruby on Rails


('a'..'z').to_a.shuffle[0..7].join

Stolen from the book I bought, somehow I remembered it.

How do you make some of them capitals? Well you could make another array with all caps, then take some from one array and the other array. Might be a better way. But that’s the easiest way.


s1 = ('a'..'z').to_a.shuffle[0..3].join
s2 = ('A'..'Z').to_a.shuffle[0..4].join
a = s1.split('') + s2.split('')
a.shuffle[0..8].join

That might work, didn’t test it though. Not on linux computer. And that isn’t very good, need some capitals in the middle. Oh do another shuffle. You might want to change how many caps are in the second string. Probably only need two.

You can see the password generator in action here. Full code below.


s1 = ('a'..'z').to_a.shuffle[0..9].join
s2 = ('A'..'Z').to_a.shuffle[0..2].join
s3 = (0..9).to_a.shuffle[0..1].join
c = ['!', '@', '#', '%', '^', '&', '*']
a = s1.split('') + s2.split('') + c.shuffle[0..2] + s3.split('')
p = a.shuffle[0..a.count-1].join

I forgot to put numbers in it. Got to have numbers in a random password.