如何在 Ruby 中生成随机字符串 [英] How to generate a random string in Ruby
问题描述
我目前正在为 "A" .. "Z" 生成一个 8 字符的伪随机大写字符串:
I'm currently generating an 8-character pseudo-random uppercase string for "A" .. "Z":
value = ""; 8.times{value << (65 + rand(25)).chr}
但它看起来并不干净,并且不能作为参数传递,因为它不是单个语句.为了得到混合大小写的字符串 "a" .. "z" 加上 "A" .. "Z",我将其更改为:
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}
但它看起来像垃圾.
谁有更好的方法?
推荐答案
(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(" ")
此代码生成 50 个单词长度小于 10 个字符的随机单词字符串,然后用空格连接
this code generates 50 random word string with words length less than 10 characters and then join with space
这篇关于如何在 Ruby 中生成随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!