HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrubyCritical

How to generate a random string in Ruby

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howrandomgeneraterubystring

Problem

I'm currently generating an 8-character pseudo-random uppercase string for "A" .. "Z":

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


but it doesn't look clean, and it can't be passed as an argument since it isn't a single statement. To get a mixed-case string "a" .. "z" plus "A" .. "Z", I changed it to:

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


but it looks like trash.

Does anyone have a better method?

Solution

(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


If you want to generate some random text then use the following:

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


this code generates 50 random word string with words length less than 10 characters and then join with space

Code Snippets

(0...8).map { (65 + rand(26)).chr }.join
(0...50).map { ('a'..'z').to_a[rand(26)] }.join
o = [('a'..'z'), ('A'..'Z')].map(&:to_a).flatten
string = (0...50).map { o[rand(o.length)] }.join
50.times.map { (0...(rand(10))).map { ('a'..'z').to_a[rand(26)] }.join }.join(" ")

Context

Stack Overflow Q#88311, score: 1043

Revisions (0)

No revisions yet.