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

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

但它看起来不干净,而且不能作为参数传递,因为它不是一个单独的语句。要获取混合大小写字符串“a”。。“z”加“A”。。“Z”,我将其更改为:

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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

a='';8.times{a<<[*'a'..'z'].sample};p a

or

8.times.collect{[*'a'..'z'].sample}.join

其他回答

如果您使用的是UNIX,并且仍然必须使用Ruby 1.8(没有SecureRandom)而不使用Rails,那么您也可以使用这个:

random_string = `openssl rand -base64 24`

请注意,这会生成新的shell,这非常慢,只能推荐用于脚本。

在这里加上我的美分。。。

def random_string(length = 8)
  rand(32**length).to_s(32)
end

这几乎是丑陋的,但也许是朝着正确的方向迈出的一步?

 (1..8).map{|i| ('a'..'z').to_a[rand(26)]}.join

这个解决方案需要外部依赖性,但看起来比另一个更漂亮。

安装gem fakerFaker::Lorem.characters(10)#=>“ang9cbhoa8”

为什么不使用SecureRandom?

require 'securerandom'
random_string = SecureRandom.hex

# outputs: 5b5cd0da3121fc53b4bc84d0c8af2e81 (i.e. 32 chars of 0..9, a..f)

SecureRandom还具有以下方法:

基础64随机字节(_B)随机编号

参见:http://ruby-doc.org/stdlib-1.9.2/libdoc/securerandom/rdoc/SecureRandom.html