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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

我不记得我在哪里找到了这个,但对我来说,它似乎是最好的,也是最不需要的过程:

def random_string(length=10)
  chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789'
  password = ''
  length.times { password << chars[rand(chars.size)] }
  password
end

其他回答

`pwgen 8 1`.chomp

以下是长度为8的随机字符串的一行简单代码:

 random_string = ('0'..'z').to_a.shuffle.first(8).join

您也可以将其用于长度为8的随机密码:

random_password = ('0'..'z').to_a.shuffle.first(8).join

在ruby 1.9中,可以使用Array的choice方法,该方法返回数组中的随机元素

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

https://github.com/sibevin/random_token

如果需要指定长度的字符串,请使用:

require 'securerandom'
randomstring = SecureRandom.hex(n)

它将生成长度为2n的随机字符串,包含0-9和a-f