Last Updated: February 25, 2016
·
1.71K
· hidakatsuya

Generate a ramdon string of N length in Ruby

[*'a'..'z', *'A'..'Z', *0..9].shuffle[0, N].join

3 Responses
Add your response

I prefer avoiding the creation of the full array. Like this:

length = 8
(0..length).to_a.collect { (rand() * 25 + 65).to_i.chr }.join

It generates from A..Z, from ASCII char codes.

over 1 year ago ·

@endel Thanks! It is also good like this:

Array.new(8) { rand(65..90).chr }.join
over 1 year ago ·

This works as well: rand(36**length).to_s(36)

over 1 year ago ·