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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

我只是编写了一个小gemrandom_token来为大多数用例生成随机令牌,享受~

https://github.com/sibevin/random_token

其他回答

为什么不使用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

SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')

来自Devise的东西

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

random_string = `openssl rand -base64 24`

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

另一个适用于Ruby 1.8+且速度快的技巧是:

>> require "openssl"
>> OpenSSL::Random.random_bytes(20).unpack('H*').join
=> "2f3ff53dd712ba2303a573d9f9a8c1dbc1942d28"

它得到的是随机十六进制字符串。类似的方式,您应该能够生成base64字符串('M*')。

我的2美分:

  def token(length=16)
    chars = [*('A'..'Z'), *('a'..'z'), *(0..9)]
    (0..length).map {chars.sample}.join
  end