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

但它看起来像垃圾。

有人有更好的方法吗?


当前回答

10.times do 
  alphabet = ('a'..'z').to_a
  string += alpha[rand(alpha.length)]
end

其他回答

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

来自Devise的东西

下面是一个长度为8的随机密码的简单代码:

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

使用此方法,您可以传入一个很短的长度。默认设置为6。

def generate_random_string(length=6)
  string = ""
  chars = ("A".."Z").to_a
  length.times do
    string << chars[rand(chars.length-1)]
  end
  string
end

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

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

这里有一个灵活的解决方案,允许重复数据:

class String
  # generate a random string of length n using current string as the source of characters
  def random(n)
    return "" if n <= 0
    (chars * (n / length + 1)).shuffle[0..n-1].join  
  end
end

例子:

"ATCG".random(8) => "CGTGAAGA"

还可以允许某个字符更频繁地出现:

"AAAAATCG".random(10) => "CTGAAAAAGC"

说明:上面的方法接受给定字符串的字符并生成足够大的数组。然后,它将其洗牌,取出前n个项目,然后将其合并。