我目前正在为“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}

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

我喜欢使用的另一种方法:

 rand(2**256).to_s(36)[0..7]

如果您真的对正确的字符串长度有疑问,请添加ljust:

 rand(2**256).to_s(36).ljust(8,'a')[0..7]

其他回答

我喜欢使用的另一种方法:

 rand(2**256).to_s(36)[0..7]

如果您真的对正确的字符串长度有疑问,请添加ljust:

 rand(2**256).to_s(36).ljust(8,'a')[0..7]

对于devicesecure_validable,您可以使用

(0...8).map { ([65, 97].sample + rand(26)).chr }.push(rand(99)).join
require 'securerandom'
SecureRandom.urlsafe_base64(9)

我想,到目前为止,我最喜欢雷达的回答。我会这样做:

CHARS = ('a'..'z').to_a + ('A'..'Z').to_a
def rand_string(length=8)
  s=''
  length.times{ s << CHARS[rand(CHARS.length)] }
  s
end

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

random_string = `openssl rand -base64 24`

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