Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

ruby - 如何在Ruby中生成随机字符串(How to generate a random string in Ruby)

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

(我目前正在为“ A” ..“ Z”生成一个8个字符的伪随机大写字符串:)

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:

(为了获得大小写混合的字符串“ a” ..“ z”加上“ A” ..“ Z”,我将其更改为:)

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

but it looks like trash.

(但看起来像垃圾)

Does anyone have a better method?

(有谁有更好的方法?)

  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
(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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...