Generate a ramdon string of N length in Ruby
[*'a'..'z', *'A'..'Z', *0..9].shuffle[0, N].join
Written by Katsuya Hidaka
Related protips
3 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#